简体   繁体   中英

How can I make user to input an int value and split them up to single number and put in array?

So I want to give user input an int value.

System.out.println ("How many number does your Student number has?");
tn = sc.nextInt();
int [] number = new int[tn];
System.out.println ("What is your Student number?");
for (int i = 0; i < tn; i++)
{    
number[i] = sc.nextInt();
}

So as you guys can see, after the first println If we input 2, the will print the second println twice, but i want it to be print only once, but user will only be able to place 2 digit number.

so for example if the tn was 2, the student number can only placed 10 - 99.

Unless I'm missing something your second print will only be called once. Note that you're going to need to add some validation on input, because 0 is a valid int and so in its current state your code won't limit the user to 10-99.

A much better way would be to ask them to enter the entire number and then split it in code (for example getting it as a String then splitting it and using Integer.valueOf() ).

From comment to question :

I was asked to take out all the even position of number

Assuming that the even positions of number 234567 are digits 3 , 5 , and 7 , you can do it easily by converting to string and extracting those characters, like this:

private static int[] getEveryOtherDigit(int n) {
    String s = Integer.toString(n);
    int[] result = new int[s.length() / 2];
    for (int i = 1, j = 0; i < s.length(); i += 2, j++)
        result[j] = s.charAt(i) - '0';
    return result;
}

Test

System.out.println(Arrays.toString(getEveryOtherDigit(7)));
System.out.println(Arrays.toString(getEveryOtherDigit(67)));
System.out.println(Arrays.toString(getEveryOtherDigit(567)));
System.out.println(Arrays.toString(getEveryOtherDigit(4567)));
System.out.println(Arrays.toString(getEveryOtherDigit(34567)));
System.out.println(Arrays.toString(getEveryOtherDigit(234567)));

Output

[]
[7]
[6]
[5, 7]
[4, 6]
[3, 5, 7]

The most convenient way to achieve that would be to just get the input as String and split it then to convert them to int

here's the code for that

System.out.println ("What is your Student number?");
String stuNum = scn.nextLine();

int [] number = new int[ stuNum.length() ];

for (int i = 0; i < stuNum.length(); i++) {
    number[i] = Character.getNumericValue(stuNum.charAt(i));
}

System.out.println (number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM