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);
}
Related
I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
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;
}
}
import java.util.Scanner;
class Tugas3 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String nama;
int umur,nomor;
System.out.println("Enter Your Full Name : ");
nama = input.nextLine();
System.out.println("Enter Your Age : ");
umur = input.nextInt();
input.nextLine();
System.out.println("Input Your Phone Number : ");
nomor = input.nextInt();
System.out.printf("Contact : "+nama+" "+umur+""+(char)48+""+nomor);
}
}
so i just want to input 0 number but i keep getting that error message.. any solution?
This will allow any input and evade the InputMismatchException, but there's nothing wrong with your original code. The problem is that you are trying to use incorrect inputs to test the Scanner.
package test;
import java.util.Scanner;
public class Tugas3 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String nama;
String line;
int umur = 0,nomor = 0;
System.out.println("Enter Your Full Name : ");
nama = input.nextLine();
System.out.println("Enter Your Age : ");
line = input.nextLine();
try{
umur = Integer.parseInt(line.trim());
}catch(NumberFormatException e){
System.out.println("Invalid number. Set to 0.");
}
System.out.println("Input Your Phone Number : ");
line = input.nextLine();
try{
nomor = Integer.parseInt(line.trim());
}catch(NumberFormatException e){
System.out.println("Invalid number. Set to 0.");
}
System.out.printf("Contact : "+nama+" "+umur+""+(char)48+""+nomor);
}
}
I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.
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) {
}
}
}