The program is supposed to ask the user for a number, and loops until the input is not a number (repeats if there is a number input).
My code so far:
import java.util.*;
public class MataVarden
{
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> Values = new ArrayList<Integer>();
System.out.print("Input a number: ");
Values.add(sc.nextInt());
Collections.sort(Values);
System.out.println("Values sorted: " + Values);
}
}
What do you need to do in order to break an input if a non-number is entered?
Use a while loop for these case.
Ok now, here’s an explanation of what’s happening there: –
sc.hasNextLine()checks whether there is an input to read or not. If yes then proceed to the next test!(line = sc.nextLine()).equals("")checks whether the next input is anempty stringor not. If it’s an empty string, the condition fails, and loop ends.nextLine()method, we would have to parse it to integer usingInteger.parseInt(line);try-catchblock to handle input like"abc", which will not be parsed to an integer, and will throw an exception, in which case, we break out of thewhile loopfrom thecatch block.sc.nextInt()because it does not read the newline token from the input. So, there would not be any way to know when to terminate the loop.As a side note, you should always follow Coding conventions in your code. Your variable name should start with a lowercase letter.