Checking input type...how? - java

I have the following method:
public void addStudent(){
String fName, lName;
double mGrade, fGrade;
System.out.print("\nEnter first name: ");
Scanner in = new Scanner(System.in);
fName = in.nextLine();
System.out.print("\nEnter last name: ");
lName = in.nextLine();
System.out.print("\nEnter midterm grade: ");
mGrade = in.nextDouble();
System.out.print("\nEnter final grade: ");
fGrade = in.nextDouble();
Student toAdd = new Student(fName, lName, mGrade, fGrade);
students.add(toAdd);
System.out.println("\nStudent record added.\n");
System.out.println(students.size());
}
How can I check if the user typed in something other than an integer for midterm grade and final grade? And if they entered a non-integer, I want the method to just request the user type in that value again. I'm guessing I'll have to use a do-while loop. But I don't don't know how to check the type...
Thanks!

You can use Scanner.next() and try to parse it to the type you want (ex. to integer by using Integer.parseInt(x) and if it fails (throws and exception) try to do it again.

Yes, a do-while will work best.
int midterm;
System.out.printLn("Enter midterm grade");
do
{
try {
string s = in.nextLine();
midterm = Integer.parseInt(s);
break;
}
catch (Exception e)
{
System.out.printLn("Couldn't parse input, please try again");
}
}
while (true);

You may use the method: nextInt() from Scanner
Alternatively you can check if a string is an integer like this:
if( someString.matches("\\d+") ) {
// it is
} else {
// it isn't
}

Run the input method in a loop, if user enters something other than valid integer or double, repeat asking for the input.

you can try this
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws Exception {
String input;
int ch1;
float ch2;
String ch3;
Scanner one = new Scanner(System.in);
input = one.nextLine();
try {
ch1 = Integer.parseInt(input);
System.out.println("integer");
return;
} catch (NumberFormatException e) {
}
try {
ch2 = Float.parseFloat(input);
System.out.println("float");
return;
} catch (NumberFormatException e) {
}
try {
ch3 = String.valueOf(input);
System.out.println("String");
} catch (NumberFormatException e) {
}
}
}

Related

Try and Catch InputMismatchException: Error Checking Integer - Logic Incorrect

I am trying to create a method for error checking input using a try and catch statement with the catch InputMismatch. It is not working can anyone advise why my return statement is not returning the input from the user and storing it in the integer which is called in the main class(call statement is not included).
System.out.print("Please enter the percent achieved for " + sName + ": %");
PromptErrorCheckingPercent(iPercent);
public static int PromptErrorCheckingPercent(int test){
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
while (!valid)
{
try
{
test = keyboard.nextInt();
valid = true;
}
catch(InputMismatchException e)
{
System.out.println("Invalid Input. Please enter a valid integer");
keyboard.nextLine(); //nextLine for a reason
}
}
return test;
What you need is a recursion when InputMismatchException is thrown instead of keyboard.nextLine(); //nextLine for a reason. Moreover, you do not need to pass the value in the argument/ parameter of promptErrorCheckingPercent() method because what you are trying is not allowed in JAVA.
Probably you were thinking passing that variable will help you to store the data in that variable. It is a feature of C-language that supports Pointer (address of the variable) but for the sake of security it is not allowed in JAVA.
You can look into the code below to check if it can solve your problem.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name:");
String sName = keyboard.nextLine();
System.out.print("Please enter the percent achieved for " + sName + ": %");
int iPercent = promptErrorCheckingPercent();
}
public static int promptErrorCheckingPercent() {
Scanner keyboard = new Scanner(System.in);
boolean valid = false;
int test = -1;
while (!valid) {
try {
test = keyboard.nextInt();
valid = true;
} catch(InputMismatchException e) {
System.out.println("Invalid Input. Please enter a valid integer");
return promptErrorCheckingPercent(); // Recursion by calling the method itself
}
}
return test;
}
}

how to return the tester to the beginning to ask user to input euro/gbp/cad

import java.util.Scanner;
public class CurrencyTester
{
public static void main(String[]args)
{
i want to loop from the beginning, but not to ask the user to type in for same converter, how do i do it?
CurrencyConverter one= new CurrencyConverter();
System.out.println("Convert dollar to euro/gbp/cad");
i want to ask for the input euro gbp or cad after the first loop
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
if("euro".equalsIgnoreCase(a))
{
euro
do {
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Euro:");
System.out.println("€"+one.getCurrencyE());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("gbp".equalsIgnoreCase(a))
{
GDP
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("GDP:");
System.out.println("£"+one.getCurrencyG());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("cad".equalsIgnoreCase(a))
{
CAd
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Canadian Dollar:");
System.out.println("$"+one.getCurrencyC());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
}
}
}
I tried to use while loop in the beginning ,but it doesn't work.
The main problem with your existing code is that you have duplicated the same logic in three different places. What you instead want to do is group any code that is common for all your different cases into methods or otherwise structuring your logic so you don't have to duplicate it.
Here is one way to structure your code in a more readable and maintainable way:
public static void main(String[] args) {
CurrencyConverter one = new CurrencyConverter();
do{
System.out.println("Convert dollar to euro/gbp/cad");
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
String d = enterDollars();
if( d == null )
break;
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
if( "euro".equalsIgnoreCase(a) )
System.out.println("Euro:\n€" + one.getCurrencyE());
else if( "gbp".equalsIgnoreCase(a) )
System.out.println("GBP:\n£" + one.getCurrencyG());
else if( "cad".equalsIgnoreCase(a) )
System.out.println("Canadian Dollar:\n$" + one.getCurrencyC());
}
catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
} while (true);
}
private static String enterDollars(){
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
return null;
}
return d;
}
I have put the code for getting user input in dollars into its own separate method, which makes the code easier to read. Similarly, you could further divide your code into smaller methods (like enterCurrency(), presentResult(), etc) to make your main method more readable.
You are copying and pasting similar pieces of logic. This is not good practice and typically means you should start creating functions for similar behavior. I am not sure how far into programming you are so I am going to show you a simple way to get input from the user using a single do/while and another do while for grabbing a valid dollar amount.
Put this in your main
CurrencyConverter one= new CurrencyConverter();
Scanner input = new Scanner(System.in);
System.out.println("Convert dollar to euro/gbp/cad");
HashSet<String> conversions = new HashSet<>();
conversions.add("euro");
conversions.add("gdp");
conversions.add("cad");
System.out.println("");
String userInput = "";
do {
System.out.println("enter euro/gbp/cad");
userInput = input.nextLine();
double amount = 0;
//check to see if we need to get a dollar amount
if(conversions.contains(userInput))
{
do {
System.out.println("Enter Dollars:");
String sAmount = input.nextLine();
amount = Double.MAX_VALUE;
//check it's a number before parsing
if(sAmount.matches("\\d+"))
{
amount = Double.parseDouble(sAmount);
//then set it for the object once
one.setDollar(amount);
}
else
{
System.out.println("Error when parsing dollar amount: " + sAmount);
System.out.println("Please Try again!");
}
} while (amount != Double.MAX_VALUE);
}
//check for euro
if(userInput.equals("euro"))
{
System.out.println("Euro: ");
System.out.println("€"+one.getCurrencyE());
}
else if(userInput.equals("gdp"))
{
System.out.println("GDP: ");
System.out.println("£"+one.getCurrencyG());
}
else if(userInput.equals("cad"))
{
System.out.println("Canadian Dollar: ");
System.out.println("$"+one.getCurrencyC());
}
else if (!userInput.equals("quit"))
{
System.out.println("Error with input : " + userInput);
}
} while (!userInput.equals("quit"));

How to repeat wrong inputs in one block without having to use nested loop?

Is it possible to repeat more than one try-catch statements in one block without creating another (nested) while loop or having to repeat the whole loop again?
For example:
while(true) {
//try-catch 1: if the user input is correct continue, or ask him to repeat this input
//try-catch 2: if the user input is correct continue, or ask him to repeat this input
break; //after it's done
}
Another Ex:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
while (true) {
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
scan1.next();
} catch (InputMismatchException e) {
//do something to repeat this task
}
try {
System.out.println("Enter another number: ");
scan2.next();
} catch (InputMismatchException e) {
//do something to repeat this task
}
break;
}
}
}
The flow you are describing doesn't require nested loops, but it does require two separate loops.
I think you want something like this:
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter a number: ");
scan1.next();
break;
} catch (InputMismatchException e) {
System.out.println("Error! That wasn't a number!");
// didn't reach a break statement, will repeat.
}
}
while (true) {
try {
System.out.print("Enter another number: ");
scan2.next();
break;
} catch (InputMismatchException e) {
System.out.println("Error! That wasn't a number!");
// didn't reach a break statement, will repeat.
}
}
Notice that this is a lot of repeated code, so you could improve it by extracting a method to call - something like:
private static int getNumber(String prompt, Scanner scan) {
while (true) {
try {
System.out.print(prompt);
return scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error! Try again.");
}
}
}
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
int num1 = getNumber("Enter a number: ", scan1);
int num1 = getNumber("Enter another number: ", scan2);
}
Disclaimer: my Java is rusty, so the above code may not be exactly right, but I hope you get the idea.
Here is a simple example where the application will not continue unless there is a valid number supplied.
public class TestInput
{
public static boolean validInput(Scanner scan)
{
System.out.print("Enter a number: ");
try
{
String stringNumber = scan.next();
try
{
int myInt = Integer.parseInt(stringNumber);
}
catch (NumberFormatException e)
{
System.out.println("No I meant a Number; " + stringNumber + " is not a number");
return false;
}
}
catch (InputMismatchException e)
{
return false;
}
return true;
}
public void doTheWork()
{
Scanner scan = new Scanner(System.in);
if (!validInput(scan))
{
doTheWork();
}
System.out.println("All Good");
}
public static void main(String[] args)
{
TestInput testInput = new TestInput();
testInput.doTheWork();
}
}
Here is a simple example to reuse a method to get multiple inputs
public class TestInput
{
public static int getNumberInput(String message)
{
Scanner scan = new Scanner(System.in);
try
{
System.out.print(message);
String stringNumber = scan.next();
try
{
return Integer.parseInt(stringNumber);
}
catch (NumberFormatException e)
{
return getNumberInput("No I meant a Number; " + stringNumber + " is not a number");
}
}
catch (InputMismatchException e)
{
//do something to repeat this task
}
return getNumberInput(message);
}
public void doTheWork()
{
int oneParam = getNumberInput("Enter a number: ");
int twoParam = getNumberInput("Enter another number: ");
System.out.println("Your first input is " + oneParam);
System.out.println("Your second input is " + twoParam);
}
public static void main(String[] args)
{
TestInput testInput = new TestInput();
testInput.doTheWork();
}
}

what is the error in this java code?

import java.util.Scanner;
public class Hello{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
System.out.println("Enter ur name");
String name=input.nextLine();
System.out.println("enter ur gpa");
double gpa=input.nextDouble();
System.out.println("Hi"+name+",ur gpa is "+ gpa);
}
}
I am getting Following Exception:
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:909) at
java.util.Scanner.next(Scanner.java:1530) at
java.util.Scanner.nextDouble(Scanner.java:2456) at Hello.main(Hello.java:12)
The code would work just fine f proper values were passed as expected by the program i.e string and then double. You may want to add Exception handling for it
Scanner input=new Scanner(System.in);
String name = "";
double gpa = 0;
boolean correctNameEnetered = false;
boolean correctGPAEneterd = false;
while(true){
try {
if(!correctNameEnetered){
System.out.println("Enter ur name");
name=input.nextLine();
correctNameEnetered = true;
}
}catch(InputMismatchException ex) {
System.out.println("Please provide String value for name");
continue;
}
try {
if(!correctGPAEneterd) {
System.out.println("enter ur gpa");
gpa = Double.parseDouble(input.next());
correctGPAEneterd = true;
}
}catch(NumberFormatException ex) {
System.out.println("Please provide an integer or decimal value for gpa");
continue;
}
break;
}
System.out.println("Hi"+name+",ur gpa is "+ gpa);
That can happen if you enter something other than a double as input. It's expecting a double; maybe you typed a string or something like that.
(an integer would upcast)
Your code look fine , that exception occur when you enter for example string in except double , So to solve this problem you need to catch that's exception:
try {
Scanner input=new Scanner(System.in);
System.out.println("Enter ur name");
String name=input.nextLine();
System.out.println("enter ur gpa");
double gpa=input.nextDouble();
System.out.println("Hi"+name+",ur gpa is "+ gpa);
}catch (Exception e){
System.out.println(e);
}

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

Categories

Resources