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.
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);
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.
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");
}
}
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();
}
Related
i wrote this code to control input so user cannot enter anything except integers
but problem is that: when an Exception occures, the message in Exception block is continousely printed and never ends, what i can do ?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0;
boolean success = false;
System.out.println("Enter an int numbers :");
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
}
}
System.out.println(i);
}
you should add scanner.nextLine(); in your catch block
the explenation is that you need to clear the scanner and to do so you should use nextLine()
"
To clear the Scanner and to use it again without destroying it, we can use the nextLine() method of the Scanner class, which scans the current line and then sets the Scanner to the next line to perform any other operations on the new line."
for more understanding visits the link
your code will look like this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0;
boolean success = false;
System.out.println("Enter an int numbers :");
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
scanner.nextLine();
}
}
System.out.println(i);
}
Add scanner.nextLine(); in your try and catch block. Like this
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
scanner.nextLine();
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
scanner.nextLine();
}
}
You can also add just one scanner.nextLine() in the finaly block, which should be below catch
I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}
For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}
I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException
I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);