Dealing with scanner exceptions for every input in a class - java

I want to take an integer but avoid an exception from a string input. I am having a lot of trouble with this, but it seems like it should be so basic. People have mentioned a try/catch, I did this and it worked, but once I put it in a loop I couldn't break the loop, plus I have a lot of input requests and it seems like a lot of code just for a line of input. Someone told me you can use Integer.parsInt but I can't get that to work either, so I think that's incorrect.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("enter something");
int num = Integer.parseInt(keyboard.nextLine());
System.out.println(num);
}
I tested it out and it didn't work. It still threw an exception. So what are ways I can take achieve this?
Thanks

Check something like that
Scanner sc = new Scanner(System.in);
System.out.print("Please enter an int: ");
String s = sc.next();
while(!s.matches("\\d+")) {
System.out.println("Input is not valid! Re enter an integer!");
System.out.print("Please enter an int: ");
s = sc.next();
}
int numWeight = Integer.parseInt(s);
System.out.println("Int: " + numWeight);
Like this you execute the Integer.parseInt after you are sure that the string input is an integer.

Related

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

Why do I keep getting the nosuchelementexception error?

I'm new to programming. I'm trying to get multiple inputs from the user by using Scanner class. I'm using net beans and trying to run and compile my code within the net beans IDE. The program runs and compiles whenever I do not close the scanner after asking for input. But when I attempt to close the scanner after every time I asked for input I get an the nosuchelementexception scanner closed error. In class, we were taught to close scanner after every time we ask for input from the user. My professor does this, also while using NetBeans and his program compiles and runs every time. Like me, he also only declares scanner once and uses the same variable multiple times while asking for input from the user.
import java.util.Scanner; // This allows us to use Scanner
public class GettingInput {
public static void main(String[] args) {
// ALWAYS give the user instructions. System.out.println("Enter an integer: ");
// Create a new scanner
Scanner keysIn = new Scanner(System.in);
// Specify the type of data/variable you are scanning in
int num = keysIn.nextInt();
// Close your scanner when you are done.
keysIn.close();
// ALWAYS confirm that you scanned in what you thought you did.
System.out.println("Your int: " + num);
// Repeat the process for a different data type
System.out.println("---------");
System.out.println("Enter a floating-point value:");
keysIn = new Scanner(System.in);
double num2 = keysIn.nextDouble(); // note the different method
keysIn.close();
System.out.println("Your floating-point: " + num2);
// Repeat it yet again
System.out.println("---------");
System.out.println("Now enter a string.");
keysIn = new Scanner(System.in);
String str = keysIn.nextLine(); // again, a different method
keysIn.close();
System.out.println(str);
}
}
This is code he had written, compiled and ran in class. When I try to run the same code it does not work.
I'm also using a Mac Book Pro and the latest version of Mac OS.
it happens because you closed the scanner and initiating the scanner object again. so it is better that you don't close the scanner where you know you are going to use it later again in your code, but you should do it once you are done with it.
Another thing is that, for different type of inputs you even don't need to create an entire scanner object again, you can just call appropriate methods of that scanner for your corresponding inputs type. Such that
import java.util.Scanner;
public class GettingInput {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
int num = keysIn.nextInt();
System.out.println("Your int: " + num);
System.out.println("---------");
System.out.println("Enter a floating-point value:");
double num2 = keysIn.nextDouble();
System.out.println("Your floating-point: " + num2);
System.out.println("---------");
System.out.println("Now enter a string.");
String str = keysIn.next();
keysIn.close();
System.out.println(str);
}
}

Scanner code that produces an error message instead of crashing

I need this code to produce an error message when the user tries to input a string instead of an int. How would I go about doing that?
import java.util.Scanner;
public class Testing {
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Please enter an int");
input = s.nextInt();
}
}
Check if user provided proper int with hasNextInt() method.
if validation was OK read that value with nextInt().
if value was not int you can use next() to consume it (you don't have to really use that value, but you need to take it out from scanner so you could read other values from user).
Use a loop. Check if there is an int. And if there isn't display a message. Something like,
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Please enter an int");
if (s.hasNextInt()) {
input = s.nextInt();
// ...
break;
}
System.err.printf("%s isn't an int%n", s.next());
}

scanner java validation and multiple instances

I am new to java and doing an assignment.
I have to request 3 inputs from the user and I have validation.
If I do it with only one instance of the scanner I get all messed up.
If I use three instances with a bit of workaround my code works.
Only I guess this is not best practice.
I have been reading a bit the manual regarding the scanner, but cannot understand the problem
Thanks
enter code here
Scanner input=new Scanner(System.in);
Scanner input2=new Scanner(System.in);
int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;
System.out.print("\n Please enter a number: ");
while(!input.hasNextInt()){
System.out.println("***** Error: the char inserted is not a number! *****");
String input_wrong=input.next();
System.out.print("\n Please enter a number: ");
}
input_integer=input.nextInt();
System.out.print("\n Please enter a double: ");
while(!input.hasNextDouble()){
System.out.println("***** Error: the char inserted is not a double! *****");
String input_wrong=input.next();
System.out.print("\n Please enter an double: ");
}
input_double=input.nextDouble();
System.out.print("\nPlease enter a string: ");
input_string=input.nextLine();
So I had two create 3 scanner instances and also to use a string to assign the wrong input in the while cycle to the able to prompt again.
Any suggestion?
I am sure there is a better way but I would try to understand..
Thanks!
I'm not exactly sure I understand what problem you're having, but scanner has some strange behaviors which are not immediately obvious. For instance, if you type "1234bubble" then press enter, then nextInt() will return 1234 and the next nextLine() will say "bubble". That is usually not desired behavior for inputs like this because "1234bubble" is not an integer and should have failed when the user pressed enter.
For that reason, I typically only use the function nextLine(). Then, I just process the data manually using functions like Integer.parseInt(..). That way, I can guarantee that I'm processing the whole line in a clear and obvious manner, unlike other techniques which create confusing code.
Here's how I would have written your program:
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main
{
static Random rand = new Random();
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
int input_integer = 0;
double input_double = 0.0;
String input_string = "";
double value = 0;
while (true)
{
System.out.print("Please enter an integer: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into an integer
input_integer = Integer.parseInt(text);
// Turning it into an int succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an int failed.
System.out.println("***** Error: the text inserted is not an integer! *****");
}
}
while (true)
{
System.out.print("Please enter a double: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into a double
input_double = Double.parseDouble(text);
// Turning it into an double succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an double failed.
System.out.println("***** Error: the text inserted is not a double! *****");
}
}
System.out.print("Please enter a string: ");
input_string = input.nextLine();
// This is done automatically when the program stops, but it's
// a good habit to get into for longer running programs.
input.close();
}
}

Is there an equivalent of while(scanf()==1) in java?

I have been using the following code in c and c++ for looping till user feeds the correct value till the program comes out of it:
while((scanf("%d",&num)==1)//same way in for loop
{
//some code
}
Can i some how use the same way to accept and loop the program till i keep entering let's say an integer and floating or a char or a special character breaks it.
Use :
Scanner sc = new Scanner(System.in); // OR replace System.in with file to read
while(sc.hasNext()){
//code here
int x = sc.nextInt();
//...
}
There are different variants of hasNext() for specific expected input types: hasNextFloat(), hasNextInt()..
Same goes for next() method so you can find nextInt(), nextFloat() or even nextLine()
You can go to Java doc for more info.
As proposed in comments, you can use the Scanner class.
Note you need to read the in buffer with a nextLine() when it is not an int.
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter an int: ");
while (!in.hasNextInt()) {
System.out.println("That's not an int! try again...");
in.nextLine();
}
int myInt = in.nextInt();
System.out.println("You entered "+myInt);
}
}

Categories