0

I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.

Here's what I did so far:

import java.util.Scanner;

public class apples {

public static void main(String args[]) {

    Scanner nameinput = new Scanner(System.in);

    System.out.println("Please enter your name to begin.");

    System.out.println("Hello " + nameinput.nextLine() + "!");

    Scanner ageinput = new Scanner(System.in);

    System.out.println("Please enter your age");

    if(!ageinput.hasNextInt()){

        System.out.println("Please enter an integer");

    }

    System.out.println("You've entered a valid age");

    nameinput.close();
    ageinput.close();
}

}

Here's what I want:

Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.

manniL
  • 7,157
  • 7
  • 46
  • 72
Arif
  • 712
  • 11
  • 20

4 Answers4

1
String stringAge;
do {
    System.out.println("Please Enter an int");
    stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
kylemart
  • 1,156
  • 1
  • 13
  • 25
dustinroepsch
  • 1,122
  • 1
  • 7
  • 24
  • While the regex check might be a tad too much for a newbie, the do - while loop is the natural thing to use in this case. +1 for that. – mtj Apr 26 '16 at 06:42
  • I agree about regex overdoing it. I just thought the regex would be better than catching an error or something like that – dustinroepsch Apr 26 '16 at 06:43
0

First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)

As for the actual code, here's what came to mind:

public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter your name to begin:");
        String name = scanner.nextLine();
        System.out.println("Hello " + name + "!");

        System.out.println("Please enter your age:");
        int age;
        while (true) {
            try { // Try to read in the age.
                age = scanner.nextInt();
            } catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
                System.out.println("Please enter an integer:");
                continue; // Attempt reading the age again.
            }
            break; // The input was a valid integer. Break out of the loop.
        }

        scanner.close();

        System.out.println("You've entered a valid age");
    }
}
Community
  • 1
  • 1
kylemart
  • 1,156
  • 1
  • 13
  • 25
0

As you know in Java they're 3 types of loops:

The while and do-while Statements

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:

while(condition)       # First check, if true or false
{ 
   # Body
}

do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:

do{    
       # Body executed at least once
 }while(condition);

The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied

Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.

This is your code edited:

import java.util.Scanner;

public class apples {

public static void main(String args[]) {

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name to begin.");
    System.out.println("Hello " + input.nextLine() + "!");

    System.out.println("Please enter your age");

    do{

         if(input.hasNextInt()){
                 System.out.println("You've entered a valid age");
                 break; 
              }

         else{
                System.out.println("Please enter an integer");
                input.next(); 
           }

    }while(true);

  }

}

Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.

GIZ
  • 4,409
  • 1
  • 24
  • 43
-2

Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::

public static void main(String args[]) {

    Scanner nameinput = new Scanner(System.in);

    System.out.println("Please enter your name to begin.");

    System.out.println("Hello " + nameinput.nextLine() + "!");

    Scanner ageinput = new Scanner(System.in);

    System.out.println("Please enter your age");

    while (!ageinput.hasNextInt()) {
        System.out.println("Please enter an integer");
        ageinput.next();
    }
    System.out.println("You've entered a valid age");
    nameinput.close();
    ageinput.close();
}

Using for::

public static void main(String args[]) {

    Scanner nameinput = new Scanner(System.in);

    System.out.println("Please enter your name to begin.");

    System.out.println("Hello " + nameinput.nextLine() + "!");

    Scanner ageinput = new Scanner(System.in);

    System.out.println("Please enter your age");

    for (; !ageinput.hasNextInt();) {
        System.out.println("Please enter an integer");
        ageinput.next();
    }
    System.out.println("You've entered a valid age");
    nameinput.close();
    ageinput.close();
}

Using do while

public static void main(String args[]) {

    Scanner nameinput = new Scanner(System.in);

    System.out.println("Please enter your name to begin.");

    System.out.println("Hello " + nameinput.nextLine() + "!");

    Scanner ageinput = new Scanner(System.in);
    int i = 0;
    do {
        if (i == 0) {
            System.out.println("Please enter your age");
            i++;
        } else {
            System.out.println("Please enter an integer");
            ageinput.next();
        }
    } while (!ageinput.hasNextInt());
    System.out.println("You've entered a valid age");
    nameinput.close();
    ageinput.close();
}
Abhishek
  • 2,485
  • 2
  • 18
  • 25
  • may i know what is wrong with my answer?? why the -1 ?? i wrote all what all would be useful to him... gave him the 3 implementations he asked.... all which are verified and even suggested him the way to go?? am i missing something?? – Abhishek Apr 26 '16 at 06:46
  • For one thing, there's no point in creating a new `Scanner` for every iteration. Though OP made a similar mistake. – shmosel Apr 26 '16 at 06:51
  • @shmosel - i have corrected my answer. thank you for improving my answer – Abhishek Apr 26 '16 at 07:08
  • Thanks! For a newbie, this was the easiest to understand out of all answers so I have no idea why this got downvoted. @shmosel Could you please modify the code with the while loop using just one Scanner so I understand how it works? Thanks! – Arif Apr 26 '16 at 07:15
  • @user6254638 i am happy that i helped you out... how do you want me to modify my code?? if it has answered your question dont forget to mark it as the correct answer – Abhishek Apr 26 '16 at 07:16
  • @Abhishek I was referring to shmosel's comment where he says that creating a Scanner for every instance isn't necessary. Is it corrected now? – Arif Apr 26 '16 at 07:21
  • Yes it is corrected now... i have updated my answer :) – Abhishek Apr 26 '16 at 07:25
  • may i know what is wrong with my answer? why the -1?? – Abhishek Apr 26 '16 at 07:29