How to validate scanner input using a different method? - java

import java.util.Scanner
public class Editable {
/* Return true if amount is within MIN_AMOUNT and MAX_AMOUNT
*/
public static boolean isValidAmount(double amount) {
return amount > MIN_AMOUNT && amount < MAX_AMOUNT;
}
/* Asks user to input amount until isValidAmount is true.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(system.in);
}
I'm new to Java and I've been struggling with this for quite a bit.
I'm asking for user input in main and I need it to keep asking for user input until isValidAmount returns true. I have tried multiple different solutions but can't seem to get it to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double inputAmount = 0;
try {
while (!isValidAmount(inputAmount)) {
System.out.println("Enter amount:");
inputAmount = scanner.nextDouble();
scanner.next();
}
} catch (Exception e) {
System.out.println("Input error.");
scanner.next();
}

First you only need a nextDouble. scanner.next() would read the next value and discard it. Also, try using a do while loop:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double inputAmount = 0;
try {
do {
System.out.println("Enter amount:");
inputAmount = scanner.nextDouble();
} while (!isValidAmount(inputAmount));
} catch (Exception e) {
System.out.println("Input error.");
scanner.next();
}
}
I think perhaps your inputAmount was already a valid value before prompting the user. The do while loop will always execute the statements between the brackets before checking the condition. The while loop will no execute the statements in the brackets if the condition is already false.

Just comment out scanner.next();. You don't need it. Your program is perfect otherwise. (I am assuming that MIN_AMOUNT is declared to be > 0).

Related

How to restart the main method?

public class Main {
public static void main(String[] args) {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if(sayiyaz.hasNextInt()) {
int sayi1 = sayiyaz.nextInt();
}
else {
System.out.println("I wish u could know what is a math value .");
}
}
}
In the else block of code i want to restart the "main" method from the beginning and ask the same question.
But how to do that ?
You can call it if you want to (like Sudhakar sugested) but i assume that you just want to request the input until you get something that fits your needs in that case you have a better solution
public static void main(String[] args) {
boolean done = false;
Integer sayi1 = null;
do {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if (sayiyaz.hasNextInt()) {
sayi1 = sayiyaz.nextInt();
done = true;
} else {
System.out.println("Input is wrong ");
}
} while (!done);
System.out.println("Here is youre input " + sayi1);
}
The answer is that you don't want to restart main. This is the entry point used by the Java Virtual machine to start your application. The simplest way to do what you want is to use a loop, so something like:
while (true) {
System.out.println("Please enter a math value");
// The rest of your code.
if (finished)
break;
}

Java Scanner Continuous User input?

For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you

Inputing Integers error throwing

Can someone help me make this code neater. I would rather use parse int than a buffer reader. I want my code to loop until the user inputs a number. I couldn't figure out how to do this without the code printing out the same statement twice.
public void setAge()
{
try {
age = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("What is your age?");
this.setAge();
}
}
Alright, my question is unclear. I am unsure of how to handle the error that a scanner throws when you don't input an integer. How do I handle this? I found "NumberFormatException" in a different post, but I am unsure of what this does. Can anyone help me with this, or is my question still unclear?
Try this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scanner = null;
int age = -1;
do {
try {
scanner = new Scanner(System.in);
System.out.println("What is your age?");
age = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a number!");
}
} while (age == -1);
System.out.println("You are " + age + " years old.");
if (scanner != null)
scanner.close();
}
}
I get this output (the first time I enter abc instead of a number to make it retry):
What is your age?
abc
Please enter a number!
What is your age?
35
You are 35 years old.
Have fun!
Use scan.nextInt(); instead of scan.nextLine();
With this, you don't need to parse the line.
EDIT: Oops, i misread your question
Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
The conversions are done by the functions Integer.parseInt.Consider if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value and NumberFormatException will occurs
You could use a scanner.
You'll need to;
import java.util.*;
static Scanner console = new Scanner(System.in);
You won't need the parse statement at all.
age = console.nextInt();
EDIT: Editing my answer after seeing your edit.
I would put the entire try in a do loop. Using a new boolean variable to control when you come out of it.
boolean excep;
do {
excep = false;
try {
age = console.nextInt();
}
catch (Exception exRef) {
System.out.println("Please input an integer");
console.nextLine();
excep = true;
}
} while (excep);
The console.nextLine() just clears a line so it doesnt re-read the last input. Sometimes it's needed.
Using this i don't receive any error notifications on the running of it.
Try this:
static boolean firstTime = true;
public static void main(String[] args) {
boolean firstTime = true;
setAge();
}
public static void setAge()
{
if(firstTime)
{
System.out.println("What is your age?");
firstTime = false;
}
Scanner scan = new Scanner(System.in);
try{
int age = scan.nextInt();
System.out.println(age);
}
catch(InputMismatchException e)
{
setAge();
}
}
if you want to print different messages you would have to do like:
import java.util.Scanner;
public class Numbers {
public static void main(String args[]) {
Numbers numbers = new Numbers();
numbers.setAge();
}
private boolean alrearyAsked = false;
private int age = 0;
static Scanner scan = new Scanner(System.in);
public void setAge()
{
try {
age = scan.nextInt();
} catch (NumberFormatException e) {
if (alrearyAsked) {
System.out.println("you typed a wrong age, please try again.");
}
else {
System.out.println("What is your age?");
}
this.setAge();
}
}
}

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");
}
}
}

Prevent input error

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);
}
}
}

Categories

Resources