> How to put string in a string array and int in an int array using scanner?

How to put string in a string array and int in an int array using scanner?

Posted at: 2014-12-18 
Since the input doesn't come in pairs, you can't use a for loop to generate index values for your arrays.

This is much easier using ArrayList or LinkedList objects because you're not tempted to use a for loop in the first place. See Mateo's answer.

For arrays, you need to keep track of the number of entries used in each array, using separate variables. Something like:

int intValues[] = new int[20];

int intCount = 0;

int strValues[] = new String[20];

int strCount = 0;

Scanner sysin = new Scanner(System.in);

while (intCount+strCount < 20) { // get 20 total, say

.... if (sysin.hasNextInt()) {

.... .... intValues[intCount++] = sysin.nextInt();

.... }

.... else {

.... .... strValues[strCount++] = sysin.next();

.... }

}

The key idea in the loop is to use if/else to add just one value to one array, and you can't do that if you don't keep separate counters of locations used in each array. You won't know where to put the new value.

Note that I allocated eash array to the maximum total number of input values (20 in the sample). That allows the input to be all ints or all strings without running out of room in either array. Your application needs might be different.

You need to add another comma on line 5.

import java.util.*;

public class Prog1

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

String str;

ArrayList numbers = new ArrayList();

ArrayList strings = new ArrayList();

do

{

str = sc.next();

if(str.equals("Quit"))

break;

if(isNumeric(str))

numbers.add(Integer.parseInt(str));

else

strings.add(str);

} while(true);

System.out.println("\n\nStrings:");

for (int i = 0; i < strings.size(); i++)

System.out.println(strings.get(i));

System.out.println("\n");

System.out.println("Numbers:");

for (int i = 0; i < numbers.size(); i++)

System.out.println(numbers.get(i));

System.out.println();

}

public static boolean isNumeric(String str)

{

try

{

Double.parseDouble(str);

}

catch(NumberFormatException nfe)

{

return false;

}

return true;

}

}

http://pastebin.com/yGNQLNTB

If I input something like this

random

string

verb

1

2

3

java

5

then the output would look like this

[random,string,verb,java]

[1,2,3,5]

I tried to use a for loop for both but i keep getting this a a result:

[random,string, verb,null,null, null, java]

[0, 0, 0, 1,2,3,0,5]