how to input string and integers into 2 diff arrays at a time?
Below is my code, im trying to change the code such that the array num[] will store integers, and the 2nd input within the code will store Strings to the array num1[].
Do i have to keep declaring the Scanner and input class?
eg. Scanner in =new Scanner(System.in);
[code for integer input]
Scanner scan=new Scanner(System.scan);
[code for string put]
Is this possible using a while loop? Because i do not know how many times i will be looping as well.
package testing;
import java.util.Scanner;
public class NewClass1 {
public static void main(String[]args)
{
Scanner in =new Scanner(System.in);
int[]num=new int[2];
int []num1=new int[2];
for (int i=0;i<2;i++)
{
System.out.println("Enter a number");
num[i]=in.nextInt();
System.out.println("Enter another number");// I am trying change this part into entering a string
num1[i]=in.nextInt();
}
for (int i=0;i<2;i++)
{ System.out.println("The price of the items is "+num[i]+" and "+num1[i]);
}
}
}
Re: how to input string and integers into 2 diff arrays at a time?
No, you will only ever need one Scanner object. How you use it will depend upon how the data is formatted. Is the data in a file with an int and a String (or String and int) on each line. Or int and String each on their own line. Or....
Re: how to input string and integers into 2 diff arrays at a time?
This is what im trying to achieve, but it appears to only ask me for the "number"//first println
is there anything wrong with my code?
Scanner scan =new Scanner(System.in);
int[]num=new int[2];
String []num1=new String[2];
for (int i=0;i<2;i++)
{ System.out.println("Enter a number:");
num[i]=scan.nextInt();
System.out.println("Enter name of number:");
num1[i]=scan.nextLine();
Re: how to input string and integers into 2 diff arrays at a time?
You have fallen for the nextInt trap. In the Scanner class it has several methods (nextInt, nextDouble) that only read the number and do not consume the carriage return. So next time you call nextLine it reads the empty String between the number you entered for nextInt and the carriage return. Kludge to fix: simply make a call to nextLine after nextInt to get rid of the carraige return.