This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I am currently facing some exceptions with my code and I am not sure how I am able to solve the errors. I am attempting to gather user input using the Scanner class Java but whenever I use it, the console displays:
1. Display Drivers
2. Import Infringement File
3. Generate Suspension Report
4. Save Driver Records
5. Exit Program
Enter a menu choice:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextByte(Unknown Source)
at java.util.Scanner.nextByte(Unknown Source)
at code.Main.validateChoice(Main.java:109)
at code.Main.main(Main.java:84)
I am using Eclipse, and it is displaying that nothing in my class is actually incorrect and there are no resource leaks to my understanding which can be causing this issue. I have spent a lot of time already trying to solve the issue but I can't manage to fix it.
I tested the same code and it works perfectly on another class file, but something is interfering with it in the main file. If I reference the code statically from another class file, the issue is not resolved and the same exception message displays.
Code is below:
public class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// Determine Driver File Location
String fileLocation = "Driver.txt";
File driverFile = new File(fileLocation);
Scanner userInput = new Scanner(System.in);
// If cannot find driver file
while (!driverFile.exists()) {
System.out.println("Cannot find drivers file. \nEnter the correct file location: ");
fileLocation = userInput.nextLine(); // enter user input for file location
}
driverFile = new File(fileLocation);
userInput.close();
// Reading From Drivers
try { // Attempt to read from file
Scanner inputFile = new Scanner(driverFile);
inputFile.useDelimiter(",");
ArrayList<Driver> drivers = new ArrayList<>();
int counter = 0; // Set counter for each iteration
while (inputFile.hasNext()) {
try {
drivers.add(
new Driver(inputFile.nextInt(), inputFile.next(), inputFile.next(), inputFile.next(),
inputFile.next(), inputFile.next(), inputFile.nextShort(), inputFile.nextByte()));
// Enter correct value of last string
String temp = inputFile.nextLine();
if (temp.equals(",Valid")) {
drivers.get(counter).setLicenceStatus("Valid");
}
else if (temp.equals(",Suspended")) {
drivers.get(counter).setLicenceStatus("Suspended");
}
else { // if input was not correct, end input and show an exception has been made
System.out.println("Licence Status incorrect, bad data in file ");
break;
}
// Data check licenceClass
if (drivers.get(counter).verifyLicenceClass() == false) {
System.out.println("Licence Class incorrect, bad data in file ");
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad data in file ");
break;
} // end catch
counter++;
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("The driver file was not found");
} // end missing driver file catch
// Menu Items
String[] firstMenuItems = {"Display Drivers", "Import Infringement File",
"Generate Suspension Report", "Save Driver Records", "Exit Program"};
final int firstMinMenu = 1; // menu values
final int firstMaxMenu = 5;
byte choice;
do {
displayMenu(firstMenuItems);
choice = (byte) validateChoice(firstMinMenu, firstMaxMenu);
// System.out.println("Your menu choice was " + choice);
} while (choice != firstMaxMenu);
} // end main
/*
* Methods
*/
public static void displayMenu(String[] menu) {
for (int i = 0; i < menu.length; i++) {
System.out.println((i + 1) + ". " + menu[i]);
}
System.out.println("Enter a menu choice: ");
}
// Determine if choice is in range
public static int validateChoice(int min, int max) {
int input = 0;
do {
input = userInput.nextByte();
if (input < min || input > max) {
System.out.println("Please enter a menu choice in range");
}
} while (input < min || input > max);
return input;
}
}
Would appreciate any help. Thanks.
Edit: Removing the userInput.close(); near the top of the code fixed it. Also will realized I had multiple userInputs. Thanks for the replies!
You are doing numerous inputFile.next() when instantiating a new Driver. Each one consumes an element. Just assign it once to a variable at the beginning and use that one.
Related
this error seems to be a very common issue. I've looked up on other Stack Overflow posts that ask about this and tried to implement their solutions, but I'm still getting the same error. The complete error is:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at src.file.main(file.java:29)
I'm sure there's something really simple I'm missing, but I can't quite find it as when I read through my code, the logic seems good. This is my file:
public class file {
public static void main(String[] args) throws IOException {
int choice = 0;
Scanner myVal = new Scanner(System.in);
while(choice != 3) {
System.out.println("1. enter info \n2. print info \n3.exit");
System.out.println("Enter a choice: ");
choice = myVal.nextInt(); //Line 29
if(choice == 1) {
enterInfo();
}
else if(choice == 2) {
print();
}
else if(choice == 3) {
System.exit(0);
}
}
}
static ArrayList<newType> studInfo = new ArrayList<src.newType>();
static void enterInfo() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the information (Program year average lastname): ");
String info = keyboard.nextLine().trim();
if(info.isEmpty()) {
System.out.println("Error, no input was made.");
keyboard.close();
return;
}
String[] tokens = info.split(" ");
int size = tokens.length;
String prgm = tokens[0];
int yr = Integer.parseInt(tokens[1]);
String lastname = tokens[3];
Double avg = Double.parseDouble(tokens[2]);
newType inf = new newType(prgm, yr, avg, lastname);
studInfo.add(inf);
System.out.println("Information added.");
keyboard.close();
return;
}
Example input: math 5 76 Smith, this information is added to the arraylist of type newType where it can be printed, or another profile can be added.
The program compiles without errors or warnings, and I can successfully run the program. When I choose option 1, I enter all the information, in the correct format, to which I get the information added message, signaling it was a successful process. After this message, the exception appears. This leads me to believe the error doesn't actually lie within my enterInfo function, as I first thought, but rather when it reaches line 29 for the second time. I don't know how to fix this error, could anyone help? Thanks in advance!
Apart from the mistakes done in using Scanner, the standards followed in java is also missing.
Classname should start with caps (file should be as File, same with newType as well. It should be NewType)
If you are naming any class then it should be a noun and so should be named as per the goal to be achieved in the program such as AddingNumbers, ReverseNumbers.
Pls refer here why we shouldn't use multiple scanner in a program : Why does closing a scanner seem to break new scanners?
I have made few changes in your code.Hope this works !!!
// modified code
public class File {
static Scanner myVal = new Scanner(System.in); // Use this scanner throughout the program
static ArrayList<newType> studInfo = new ArrayList<src.newType>();
public static void main(String[] args) throws IOException {
int choice = 0;
while (choice != 3) {
System.out.println("1. enter info \n2. print info \n3.exit");
System.out.println("Enter a choice: ");
choice = myVal.nextInt(); // Line 29
if (choice == 1) {
enterInfo();
} else if (choice == 2) {
// print();
} else if (choice == 3) {
System.exit(0);
}
}
myVal.close(); // Can be closed once the need is over.
}
static void enterInfo() {
// Scanner keyboard = new Scanner(System.in); No need of multiple scanners.
System.out.println("Enter the information (Program year average lastname): ");
String info = myVal.nextLine().trim();
if (info.isEmpty()) {
System.out.println("Error, no input was made.");
// keyboard.close();
return;
}
String[] tokens = info.split(" ");
int size = tokens.length;
String prgm = tokens[0];
int yr = Integer.parseInt(tokens[1]);
String lastname = tokens[3];
Double avg = Double.parseDouble(tokens[2]);
newType inf = new newType(prgm, yr, avg, lastname);
studInfo.add(inf);
System.out.println("Information added.");
// keyboard.close();
return;
}
}
This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 2 years ago.
I am trying to figure out how to read input from the console in Java that would behave exactly the same as the following C++ code:
while(cin >> input)
I essentially need to keep reading the console one integer at a time, and only stop when the user enters no more integers.I am able to read integers one at a time, but cannot figure out how to get it to stop executing once the user passes an empty line. Thanks!
Scanner scanner = new Scanner(System.in);
// find the next int token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a int, print found and the int
if (scanner.hasNextInt()) {
System.out.println("Found :" + scanner.nextInt());
}
// if no int is found, print "Not Found:" and the token
System.out.println("Not Found :" + scanner.next());
}
You can use the Scanner nextLine() method and check for integers:
import java.util.*;
class TextNum {
public static void main(String[] args) {
int n;
String s;
Scanner in = new Scanner(System.in);
while (true) {
s = in.nextLine();
//Do something with this
System.out.println("This is :" + s + ":");
try {
n = Integer.parseInt(s);
} catch (Exception e) {
break;
}
}
}
}
I am coding a rainfall averaging program. The program lets the user input a file name and if the file cannot be found, then the user is prompted to reenter the file name. The user gets 4 tries before the application quits without processing the data, and the application itself is a rainfall averaging program like I said.
package experiment8;
import java.io.*;
import java.util.Scanner;
public class Exceptions
{
static Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println("Enter file name>");
fileName = inName.nextLine();
boolean fileOk;
do
{
fileOk = false;
try
{
Scanner scan = new Scanner (System.in);
Scanner file = new Scanner(new File("inData.dat"));
fileOk = true;
}
catch(FileNotFoundException error)
{
System.out.println("Reenter file name>");
fileName = inName.nextLine();
fileTry++;
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile = new PrintWriter(new FileWriter("outData.dat"));
if (fileOk && fileTry < 4 )
{
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0)
System.out.println("Average cannot be computed " +
" for 0 days.");
else
{
average = total / numDays;
outFile.println("The average rainfall over " +
numDays + " days is " + average);
}
inFile.close();
}
else
System.out.println("Error");
outFile.close();
}
}
I am trying to code this program so when I input the correct file name, "inData.dat", I will get the proper output. However, when I do this, I continue to get prompted to reenter the file name for the next 3 times, after which I get the "Error" message. Is there something wrong with my try/catch blocks or if statements?
There are lot of issues with your program. Here are a few to get you on the way.
The file inData.dat does not exist. Please create it in the appropriate place.
After you get over that hump, there would be a Null Pointer on Line 40: inFile is null.
My recommendation is to open it in an editor such as Visual Studio Code. It would point you to a lot of warnings and you could debug your program as well.
I have two questions about your code.
What is the purpose of the line Scanner scan = new Scanner (System.in); in the try-block?
Why do you have an if statement check if (fileOk && fileTry < 4) after the do-while block for getting the file? It seems redundant. The do-while block checks for the same condition. Once the program gets to the location of this if-statement this condition must have been met. If it wasn't, the do-while would have run again.
It is possible for you to get to a case where the do-while ends because the file was found, and the condition of this if-statement is false because fileTry < 4. I don't understand why you would care about the fileTry counter once you found the correct file. If the user tried to enter the file name 4 times and got it correct on the last try, the program will go to the else part of this if-statement and print "Error".
like in the title , I'm stuck with this error for a while .I get the value from the file normally but when I try to convert it the error poops out. I read many topics ,but couldn't find any similar case to mine(with file) or any good tips. I tried adding an assert ,but it didn't help. The full description of error is :
Exception in thread "main" java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:620)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at EnergyMeasure_needs_to_be_completed.main(EnergyMeasure_needs_to_be_completed.java:85)
Also I'm beginner (but I guess you already know that heh ;))
import java.util.Scanner;
import java.io.*;
public class EnergyMeasure_needs_to_be_completed {
public static void main(String[] args) throws IOException {
//int work_of_energy;
Scanner input = new Scanner(System.in);
System.out.println("\t\t\t\t Hi , this program will count how many kWh you're using");
//asks about number of devices
System.out.println("First of all, how many the same devices do you have in your house ?");
int devices = input.nextInt();
boolean bool = false;
do {
if (devices < 0) {
System.out.println("You can't have less than 0 devices in your home!\nMake input once again :");
devices = input.nextInt();
} else {
System.out.println("Okay, so you've got " + devices + " same devices.");
bool = true;
break;
}
}while(bool = true);
//asks about time of use
System.out.println("\nHow many hours you use them per day?");
int time_use = input.nextInt();
do {
if (time_use > 24 || time_use < 0) {
System.out.println("Wrong!\nMake input once again :");
time_use = input.nextInt();
}
else{
System.out.println("You use your devices for " + time_use + "h");
bool = true;
break;
}
}while(bool = true);
/*else if(!input.hasNextInt()){
System.out.println("Invalid input! \nEnter an integer : ");
time_use = input.nextInt();
} */
//downloads value of power from file
String power_dev; //path to the file
power_dev = null; //reference to one line at a time
try {
FileReader fileReader = //reads text files in the default encoding
new FileReader("power_monitors");
BufferedReader bufferedReader = //deal with a line at a time
new BufferedReader(fileReader);
while((power_dev = bufferedReader.readLine()) != null) {
System.out.println("\nThe power of your devices is " + power_dev + "W");
}
bufferedReader.close(); //close file
}
catch (FileNotFoundException e) { //if file doesn't exist catch the except
System.out.println("Unable to open file");
}
//assert power_dev != null;
int power_dec = Integer.parseInt(power_dev); //change the String ,to Integer
int power_of_devices = power_dec * devices; //summary devices power
//count the cost of work (W = P * t) [kWh]
int work_of_energy = (power_of_devices / 1000) * time_use;
System.out.println("The work of energy equals : " + work_of_energy);
}
}
If you print power_dev, what do you get? What format is it? Because the readLine() returns a textual line, so depending on the source you are reading from, you might get more than an int.
Why not use the read() method? It returns an int, so you wouldn't have to parse power_dev.
Again, hard to answer your question without seeing the file or having a reproductible code, but my best guess is that power_dev returns null or something that can't be parsed by Integer.parseInt() method.
This question already has answers here:
Scanner close after use
(2 answers)
Closed 3 years ago.
When I run my code, it will run fine up to the line "scanner.close()".
After than, when I run the "SumTenNumbers()" method... it will run the first line of the while loop once and crash with the "NoSuchElementException"...
When I remove the code above the line calling the method, it runs fine...
Why does this occur, and how can I solve it?
This is the code:
public class Main
{
public static void main(String[] args)
{
// we use the class "scanner" for input data
Scanner scanner = new Scanner(System.in); //System.in allows you to type input data into the console which can be returned into the console
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Your name is " + name);
System.out.println("Enter your year of birth: ");
boolean isInt = scanner.hasNextInt();
if (isInt)
{
int yearOfBirth = scanner.nextInt();
int age = 2019 - yearOfBirth;
if (age >= 0 && age <= 120)
{
System.out.println("You are " + age + " years old");
}
else
{
System.out.println("Invalid year of birth");
}
}
else
{
System.out.println("Unable to parse year of birth");
}
scanner.close(); // we must close scanner
SumTenNumbers();
}
public static void SumTenNumbers()
{
var reader = new Scanner(System.in);
int sum = 0;
int count = 1;
while (count < 11)
{
System.out.println("Enter number " + count + ": ");
boolean valid = reader.hasNextInt();
if (valid)
{
int userNum = reader.nextInt();
sum += userNum;
count++;
}
else
{
reader.next();
System.out.println("INVALID");
}
}
System.out.println(sum);
reader.close();
}
}
This is how it looks when I run the code...
Enter your name:
Siddharth
Your name is Siddharth
Enter your year of birth:
2001
You are 18 years old
Enter number 1:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at com.company.Main.SumTenNumbers(Main.java:64)
at com.company.Main.main(Main.java:39)
Process finished with exit code 1
the line reader.close() closes the Scanner and, with it, System.in.
After that, you cannot read from stdin (System.in) anymore.
In order to prevent this you can:
use only one Scanner object and close it after using it the last time
close System.in after using it the last time (using a Scanner or System.in.close())
close System.in at the end of your Program
never close System.in (Problem: other Processes cannot use the resource, stdin can also be a File, a Network Connection or something else)