Prevent input error - java

import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?

The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}

This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}

Related

Is there a method to validate whether a user input for an list index is within the list bounds and not a string?

Currently I have a code that looks like this
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = input.nextInt();
status[verify(status,userInput)] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[],int userIndex){
while(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
userIndex = input.nextInt();
}
return userIndex;
}
}
The "verify" method is used to check whether the user enters an index which is out of Bounds.
I am wanting to extend the "verify" method to check if the user enters a string but am not sure how to do that. I want a message to be displayed saying that the user has entered a string and want to keep getting the user input until a correct array index is entered.
Is there any way to check whether a string is entered, in the same method?
Actually, nextInt method on Scanner class will throw you an InputMismatchException if the user inputs something that's not Integer. Take a look at nextInt method signature. If you want, you can catch that exception and log message that you want into the console.
Take a look at the following code. Hope it works for you.
Java
import java.util.Arrays;
import java.util.Scanner;
public class Scan {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = verify(status, input);
status[userInput] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[], Scanner input){
do {
int userIndex=-1;
String line = input.next();
try {
userIndex = Integer.parseInt(line);
}catch(NumberFormatException e) {
System.out.println("Please enter a number.");
continue;
}
if(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
continue;
}else {
return userIndex;
}
}while(true);
}
}

Java while loop not breaking after "break" statement

import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
while(true){
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}
The user should be able to put in multiple numbers until -1 is reached. Once its reached it should break the loop and print the last line.
You need to put
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
into your loop, else it will never get new user input
You need call scanner inside loop
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}

Java exception handling

so I'm kind of new to catching errors and such. Anyways, the program is supposed to ask the user for 2 integers and then add them together. Simple, but if either of the numbers are not integers, than an error is thrown. Currently, if I enter 2 integers, instead of adding them, it just restarts the getAnswer() method and outputs them again. Also, if you enter more than one error, it will simply exit.
package javaapplication1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Intro();
System.out.println("Your answer: "+getAnswer());
}
private static void Intro() {
System.out.println("Hello this program adds 2 integers together and catches errors.");
getAnswer();
}
private static int getAnswer() throws InputMismatchException {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown");
return 0;
}
}
}
You are calling getAnswer(); totally two times, so you just remove the call from Intro() method which will solve the problem.
private static void Intro() {
System.out.println("Hello this program adds 2
integers together and catches errors.");
}
If you want to prompt the user to reenter the input again, you can call the getAnswer() in the catch block as shown below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown, please reenter values:");
getAnswer();
}
return 0;
}
One more point is that rather than catching the InputMismatchException, the other better way is read the inputs as strings and validate that they contain only numeric values like below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a number");
String num1 = scanner.nextLine();
System.out.println("Please input a second number");
String num2 = scanner.nextLine();
if(num1.matches("[0-9]+") && num2.matches("[0-9]+")) {
return Integer.parseInt(num1)+ Integer.parseInt(num2);
} else {
System.out.println(" Your inputs contain Invalid characters");
getAnswer();
}
return 0;
}

Need to have a string "Enter a number: " repeat

As the title said I need to enter a string "Enter a number: " repeat itself after I've entered multiple values until I enter "DONE."
So for example it should look like this:
Enter a number:
4
Enter a number:
53
Enter a number:
DONE //closes program
This is a small part to a larger program and granted I know its simple, but I cant figure this out :[
What I'm guessing and been trying is a public static class with a toString method. But I can only get one "Enter a number: " printed once.
Enter a number:
4
53
DONE //closes program
Thanks in advance.
Some code I have for this part would be:
import java.util.Scanner;
public class EnterANumba
{
public static void main(String[] args)
{
while() //Stuck here
{
System.out.println("Enter a number:");
}
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine())
{
word = scanner.nextLine();
if (word != null)
{
word = word.trim();
if (word.equalsIgnoreCase("done"))
{
break;
}
}
else
{
break;
}
}
I guess this following code snippet may help you.
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a number:");
while(!(s.next().equalsIgnoreCase("DONE"))){
System.out.println("Enter a number:");
}
}
}
try asking for the 1st time and then make a loop where you validate the input and ask until the condition is met...
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!("done".equalsIgnoreCase(scanner.next()))) {
System.out.println("Enter a number:");
}
System.out.println("Enter a number:we are done....");
}

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Categories

Resources