2

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);
    }
}
Pete C.
  • 135
  • 2
  • 9
  • possible duplicate of [Scanner issue when using nextLine after nextInt](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint) – assylias Nov 17 '12 at 10:33

2 Answers2

3

Scanner.nextInt method only reads the next token from the input passed from user. So, it ignores the linefeed that is at the end of each input. And that linefeed goes as input to the next call to Scanner.nextInt, and hence your input is ignored.

You can use a blank Scanner.nextLine after each call to Scanner.nextInt to consume the linefeed.

if(scanner.hasNextInt()){
    int x = scanner.nextInt();
    scanner.nextLine();  // Add a blank nextLine
    list.add(x);
    System.out.println("user input: " + x);
}

Or you can also use scanner.nextLine() only for reading integers, and convert the input to integer using Integer.parseInt.

if(scanner.hasNextInt()) {
    int x = 0;

    try {
         x = Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException e) {
         e.printStackTrace();
    }

    list.add(x);
    System.out.println("user input: " + x);
}

Actually, since you are using scanner.hasNextInt in your if, you don't really need that try-catch around your Integer.parseInt, so you can remove that.


UPDATE : -

I would replace your do-while with a while and just remove the if-else check from inside.

while (scanner.hasNextLine()) {
    String input = scanner.nextLine();

    if (input.equals("End")) {
        break;
    } else {
        try {
            int num = Integer.parseInt(input);
            list.add(num);

        } catch (NumberFormatException e) {
            System.out.println("Please Enter an Integer");
        }
    }
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Wow that's one quick response! Didn't expect this quick, thank you for that! :D For the if-else, silly me, didn't notice that. :P – Pete C. Nov 17 '12 at 10:56
  • Unfortunately the solutions do not work with me. I am using Eclipse IDE, not sure if it would affect anything. – Pete C. Nov 17 '12 at 11:41
  • @PeteC... No using Eclipse would not affect anything. I think it should work. Let me see your code. – Rohit Jain Nov 17 '12 at 11:45
  • @PeteC... Its better to replace your `do-while` with a `while` to avoid doing multiple test. See my update. As you can see, it uses just `one scanner.hasNextLine()` as opposed to `4 scanner.hasNext***` in your do-while. – Rohit Jain Nov 17 '12 at 11:54
2

The mistake in the code you posted is that you are creating a new Scanner object with ever iteration of your loop. Initialize the scanner before the loop and your code works:

    scanner = new Scanner(System.in);
    do {
      if(scanner.hasNextInt()){
            int x = scanner.nextInt();
            list.add(x);
            System.out.println("user input: " + x);
        }
        //and so on...

BTW - the max and min values can be calculated inside the while loop without first storing the values in a List.

Thank you for calling this free on-line class to my attention.

Thorn
  • 4,015
  • 4
  • 23
  • 42
  • That would indeed be better but he would still have the issue if he does not consume the `\n` after calling `nextInt()`. – assylias Nov 17 '12 at 10:42
  • @Thorn... I did that for some reason, but I can't remember that now. The course is great for beginners like me. It explains a lot of concepts that other online tutorials don't have. – Pete C. Nov 17 '12 at 12:27
  • @Thorn... I have also revised my code to calculate the max/min values inside the loop. That's a good advise, makes the code less messy, thanks! – Pete C. Nov 17 '12 at 12:51