How do I change this while(true) into a do while so when the user enters a number they will be given back details but if they enter * the system will close.
while (true){
System.out.print("Enter number: ");
int option = keyboard.nextInt();
out.writeInt(option);
char option;
do {
System.out.print("Enter number: ");
option = keyboard.nextChar();
out.writeChar(option);
} while (option != '*')
You may want to use nextLine() or next() to receive the input and parse them accordingly:
do{
System.out.print("Enter number: ");
String str = keyboard.nextLine();
int option = 0;
if(str.matches"[0-9]+"){
option = Integer.parseInt(str);
System.out.println(option);
}
else if(str.equals("*"))
System.exit(0); //or use break; if you want to exit the loop
}while(whatever); //whatever == true
If you change it to allow the user to input a String and then convert to int if possible, you can catch any errors and break out if the user enters a '*' character:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option;
String input;
do{
System.out.print("Enter number: ");
input = keyboard.nextLine();
try{
option = Integer.parseInt(input);
System.out.println("You entered the value: " + option);
}
catch(Exception ex) {
if (!input.equals("*")){
System.err.println("Invalid input, please enter numbers only.");
}
}
}while(!input.equals("*"));
}
}
If you use an exit value like (-1), you can continue to process input with nextInt() and becomes even easier. You can do this with a simple do/while:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option = 0;
do{
System.out.print("Enter number: ");
option = keyboard.nextInt();
System.out.println("You entered the value: " + option);
}while(option != -1);
}
}
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
}while(!str.equals("*"))
edit: if you want to play with numbers as integer or double. Just let me know and I'll add casted version as your needs.
int number;
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
number = Integer.parseInt(str);
}while(!str.equals("*"))
now you have a integer number.
Related
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 1 year ago.
As the title says, i'm attempting to make my program re-ask for user input if the given input is invalid (In this case, invalid input is any input that is not an integer)
I've already tried this, but it does not work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
} else {
System.out.println("This input is not an integer - Please try again!");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
System.out.println();
}
}
}
I'm aiming for this to be done with while loop and scanner
My current code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
if (scanner.hasNextInt()) {
int age = scanner.nextInt();
System.out.println("Your age is: " + age);
}
}
}
Any reply on this post is greatly appreciated.
You can use while-loop:
Scanner scanner = new Scanner(System.in);
boolean ageGiven = false;
while (!ageGiven) {
System.out.println("Please input your age");
String next = scanner.next();
try {
int age = Integer.parseInt(next);
System.out.println("Your age is: " + age);
ageGiven = true;
} catch (NumberFormatException e) {
System.out.println("This input is not an integer - Please try again!");
}
}
I think you should put while instead of if statement. Break after having correct input. Try out once.
As you suggested, a while loop is more appropriate to this.
Something like this should work:
Scanner scanner = new Scanner(System.in);
System.out.println("Please input your age");
boolean isValid = false;
int age;
while (!isValid) {
if (scanner.hasNextInt()) {
age = scanner.nextInt();
isValid = true;
}
else {
System.out.println("Invalid input. Please type a number");
}
}
System.out.println("Your age is: " + age);
In this case, it would loop while the IsValid boolean is false. And that variable would be set to true, once the user inputs a valid age.
Edit: Changed the code to check if the input is an integer.
I'm trying to write a progam that prompts the user to enter the number of students followed by prompting for username and grade. It runs once (meaning I get asked the number of students, I can enter the first name and number), and then it gives an InputMismatchException.
Can you see what's wrong?
public class LowestScore {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
}
Error
run: Enter the number of students12 Enter student name Enter grade josje 8
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
demo.LowestScore.main(LowestScore.java:31) Java Result: 1
You need to catch the carriage return after each of the nextInt call.
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
input.nextLine(); // catch it
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
input.nextLine(); // catch it
}
Notice that you can still run into an exception if you enter an invalid Integer.
Edit:
Basicly the nextInt catches a number that you do input, but it doesn´t catch the carriage return (the new line you are creating by pressing enter). So what it does is, you enter a number for the amount of students, lets say 1. The nextLine call instantly gets the carriage Return, creates an empty Student name and you jump straight forward to the next nextInt call. This goes on until you reach the complet amount of students. Calling nextLine after the nextInt catches the carriage return, and you are able to input the student Name.
You can specifically notice this at the point where it does print
Enter student name
Enter grade
at the same time. You allways jump directly to the next input for an Integer.
Edit2:
if you would like to catch the Exception for a wrong input aswell, then you could do it like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfStudents = -1;
boolean exception = true;
do {
try {
System.out.print("Enter the number of students");
numberOfStudents = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
int number = 0;
while (number <= numberOfStudents) {
exception = true;
number++;
System.out.println("Enter student name");
String studentName = input.nextLine();
int grade;
do {
try {
System.out.println("Enter grade");
grade = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
// input.nextLine();
}
}
Check out this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number < numberOfStudents) {
String num = input.nextLine();
System.out.println("Enter student name");
String studentName = input.next();
System.out.println("Enter grade");
int grade = Integer.parseInt(input.next());
number++;
}
}
I'm trying to figure out how I can write this method to avoid the stack buildup from recursively calling the method in the exception?
Here is the wording of my instructions:
Read a number, use an exception handler to make sure it is an int number and then add to the ArrayList object, aryList.
Here is my attempt:
public void createOriginalAryList() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number: ");
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
System.out.println("Invalid number submitted! Try again.");
createOriginalAryList();
}
System.out.println(aryList);
}
Any suggestions are greatly appreciated!
Simply use a do-while loop:
Scanner keyboard = new Scanner(System.in);
boolean redo = false;
do {
System.out.println("Enter a number: ");
redo = false;
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
redo = true;
System.out.println("Invalid number submitted! Try again.");
}
}
while(redo);
System.out.println(aryList);
Since initializing the Scanner keyboard each time is useless, it is put before the loop.
I want the user to enter a number which is scanned by the following code:
scanner.nextInt();
If a user enters a string instead, the program throws InputMismatchException, which is obvious. I want to catch the exception in such a way that the program prompts the user to enter an input until the user enters an integer value.
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
continue;
}
}
This code creates an infinite loop if a string is entered.
The answer to my problem is as follows:
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input
continue;
}
}
Put Scanner scanner = new Scanner(System.in); within your while loop.
Scanner scanner;
while(true) {
try {
System.out.println("Please enter a number: ");
scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("I said a number...");
}
}
How about this?
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println("\n\nEntered number is : " + input);
break;
} catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("\n\nInput was not a number. Please enter number again : ");
} catch(Exception e ) {
System.out.println("\n\nException caught :: " + e);
}
}
I have also removed continue syntax as those are not needed.
I am trying to make a simple text based operating system and I cant figure out why my code doesn't let me enter a command after the calculator class is done. It is supposed to continue executing the code until I type "off" but this is not the case. Eclipse says it is running but I cant do anything. can someone please help me?
here is my two classes:
public class Calculator extends Start{
public static void calStrt() {
System.out.print("\nEnter operator you wish to use: ");
StringInput = scan.nextLine();
if (StringInput.equals("+")) {
add();
} else if (StringInput.equals("-")) {
sub();
} else if (StringInput.equals("*")) {
mul();
} else if (StringInput.equals("/")) {
div();
} else {
System.out.println("\nSyntax error: Operator not recognized");
System.out.println("Please try again");
calStrt();
}
}
public static void add() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 + intVar2));
}
public static void sub() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 - intVar2));
}
public static void mul() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 * intVar2));
}
public static void div() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 / intVar2));
}
}
import java.util.Scanner;
class Start {
static Scanner scan = new Scanner(System.in);
static String StringInput;
static int intInput;
public static void main(String[] args) {
System.out.println("\nWelcome to RobOS");
passLoop: while (true) {
System.out.print("\nPlease enter password: ");
StringInput = scan.nextLine();
if (StringInput.equals("banana")) {
System.out.print("Logging in, please wait");
System.out.print(".");
System.out.print(".");
System.out.println(".");
System.out.println("\nWelcome User");
outerLoop: while (true) {
System.out.println("\nType \"help\" to see a list of programs");
StringInput = scan.nextLine();
innerLoop: while (true) {
if (StringInput.equalsIgnoreCase("cal")) {
Calculator.calStrt();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("guess")) {
GuessGame.guess();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("help")) {
System.out.println("\n\"cal\" uses the calculator");
System.out.println("\"guess\" plays guessing game");
System.out.println("\"help\" shows list of programs");
System.out.println("\"off\" turns RobOS off");
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("off")){
break passLoop;
}
}
}
} else {
System.out.println("\nWrong password. Please try again");
continue passLoop;
}
}
}
}
Brent Nash is correct. To fix the error though, try using instead of scan.nextInt(): Integer.parseInt(scan.nextLine());
Hope this works
Your code is getting into an infinite loop. When you call StringInput = scan.nextLine(), the first time it works fine. I entered cal and I can run the calculator once. The problem is that the second time scan.nextLine() gets called, it's automatically returning an empty string "" as the value of StringInput. Your set of if/else statements in the while(true) have no way to handle this, so it just loops forever.
The deeper rationale is that you call scan.nextInt() to read in the numbers, but the problem is when you read in the second number for the calculator operation, there's still a "\n" sitting on System.in. As a result, when you loop around and call scan.nextLine() again, it doesn't prompt you for anything because it just reads that "\n" that's still sitting on System.in and then that sends you into an infinite loop.