I am trying to learn Java programming by myself and came across the course CS106A provided by Stanford. It’s a great free online course. I watched several of the lecture videos and I enjoyed them so far. I am now trying to do the assignments and I have this problem I can’t solve by myself.
It is the number 5 of this assignment. Basically, it requires the learner to create a console program to get some integers input by the user and in response, showing the biggest and smallest number.
The following code is what I have done and the problem is when I try to input integers, it will skip the even number of inputs. For instance if I enter 3,12,6,15,9 to the console, it will only get 3,6,9 , ignoring 12,15.
What did I do wrong? Any help would be appreciated.
import java.util.*;
public class Ass2_5MaxMinNumbers {
public static void main (String args[]) {
Scanner scanner;
System.out.println ("This programme finds the largest and smallest numbers.");
System.out.println ("After finished entering, enter \"End\" (without double quotes) to show the results.");
List<Integer> list = new ArrayList<Integer>();
int max = 0, min = 0;
do {
scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
int x = scanner.nextInt();
list.add(x);
System.out.println("user input: " + x);
} else if(!scanner.hasNext("End")){
System.out.println("Please enter an integer!");
}
} while (!scanner.hasNext("End"));
max = list.get(0);
min = list.get(0);
for(int x = 1; x < list.size(); x++){
if(list.get(x) > max){
max = list.get(x);
} else if(list.get(x) < min){
min = list.get(x);
}
}
System.out.println ("Smallest number: " + min);
System.out.println ("Biggest number: " + max);
}
}
Scanner.nextIntmethod only reads the next token from the input passed from user. So, it ignores thelinefeedthat is at the end of each input. And that linefeed goes as input to the next call toScanner.nextInt, and hence your input is ignored.You can use a blank
Scanner.nextLineafter each call toScanner.nextIntto consume the linefeed.Or you can also use
scanner.nextLine()only for readingintegers, and convert the input tointegerusingInteger.parseInt.Actually, since you are using
scanner.hasNextIntin your if, you don’t really need thattry-catcharound yourInteger.parseInt, so you can remove that.UPDATE : –
I would replace your
do-whilewith awhileand just remove theif-elsecheck from inside.