Why do I keep getting the nosuchelementexception error? - java

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

Related

Dealing with scanner exceptions for every input in a class

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.

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

How do I use java.util.Scanner with integers

I just started learning java and I want to make a simple program where it requests the persons
name, outputs the name then asks for the thier favorite number. It will then compare their number
to the number 6 and will output something depending on if the number is larger or smaller than 6.
I am getting a "String to int convert" error in Netbeans which has to do with the scanner.
Hopefully I am asking this correctly but how can I make the scanner pick-up integers?
Thanks
package javaapplication2;
import java.util.Scanner;
import java.lang.String;
public class JavaApplication2 {
public static void main(String[] args) {
// Creating an instance of the scanner class.
// Gets name and numbers.
Scanner getName = new Scanner(System.in);
Scanner getNumber = new Scanner(System.in);
//Holds name and number
String userName;
int userNumber;
// Asks for the users name.
// Holds name in userName.
System.out.println("What is your name?");
userName = getName.nextLine();
//Reponds with the users name.
System.out.println("Hello" + userName + "!");
//Asks for favorite number.
// Holds number in userNumber.
System.out.println("What is your favorite number?");
userNumber = getNumber.nextLine();
// Checks if users number is larger than 6.
if (userNumber > 6) {
// Stuff goes here.
}
}
}
You should use only one Scanner for one input stream:
Scanner in = new Scanner(System.in);
And after that you should use it's methods to get integers:
String name = in.nextLine();
int number = in.nextInt();
To be sure, you should read the documentation for Scanner:
Scanner
Scanner::nextLine
Scanner::nextInt
This might help: Javadoc page for Scanner.

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Categories