Alberto32 Alberto32 - 1 month ago 14
Java Question

Cycle while with scanner hasNext()

I have a problem when I try to run my work.
I have to put in some numbers by console and It should arrange in ascending order them and save to an array.
I thought that method hasNext worked well with String.nextLine(), but it seems to still in loop.
thanks for help

import java.util.Scanner;

public class OrdinamentoMaggiore{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Digita dei numeri e te li mettero' in ordine crescente: ");
String Numeri = sc.nextLine();
int dimArray = 0;
while (sc.hasNext(Numeri)){
dimArray++;
System.out.println("Dimensione array: " + dimArray);
}
int min = 0, max = 0, temp;
int[] mioArray = new int[dimArray];
for (int i = 0; i <= mioArray.length; i++){
mioArray[i] = Integer.parseInt(sc.next(Numeri));
}
for (int j = 0; j <= mioArray.length; j++){
for (int h = 1; h <= mioArray.length; h++){
if (mioArray[j] < mioArray[h]){
continue;
}
else {
temp = mioArray[j];
mioArray[j] = mioArray[h];
mioArray[h] = temp;
}
}
}
System.out.println("Min: " + mioArray[0]);
System.out.println("Max: " + mioArray[dimArray]);
sc.close();
}
}

Answer

The problem is that you are reading the first line of input into the variable Numeri. Then, you are calling hasNext on Numeri which isn't working the way you think it is. Scanner.hasNext is defined here as:

Returns true if the next token matches the pattern constructed from the specified string.

So it is using the string in Numeri as the pattern it needs to match. Definitely not what you want.

I would recommend a list and doing something like this:

    List<Integer> numberList = new ArrayList<>();
    while (sc.hasNextInt()) {
        numberList.add(sc.nextInt());
    }
    Collections.sort(numberList);

A list is nice because you don't have to explicitly tell it the size. That avoids your first loop. Now, the loop goes continues reading from System.in until it encounters something that isn't an integer and adds them to the list.

Finally, it uses Collections.sort to sort the list. How beautiful is that? Your whole program can be reproduced in just a few lines. Definitely try and learn the libraries and functions that are available to you. It can save you a lot of time and effort. Let me know if you have questions.

Comments