Exception in main thread java.util.NoSuchElementException - java

I'm working on this project to improve my skill in Java. My goal is to write a program that reads the line from a specified doc or text file (depending on which the user wants to open; int 2 or 1 respectively.) and then asks the user to input their document name (without the file extension), and then reads the first line in the document or text file. I want it to do this as many times as the user wants. But I keep getting NoSuchElementException while executing the code.
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}

If you remove the line input.close(); on line 14. This should solve your problem. According to the documentation, it will throw a NoSuchElementException - "if input is exhausted".

Related

Print to console in JAVA

I have a simple question. My program asks the user to type a name, range, and length to generate random numbers. The result will be printed into a file from the console. I want to know is it possible to print to the console that the file has been printed when it's done.
Currently this is my set up to print to a file:
Scanner s = new Scanner(System.in);
System.out.println("-----------------------------------------------");
System.out.println("Choose a name to your file: ");
String fn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your range: ");
String rn = s.nextLine();
System.out.println("-----------------------------------------------");
System.out.println("Choose your length of array: ");
String ln = s.nextLine();
System.out.println("-----------------------------------------------");
int rangeToInt = Integer.parseInt(rn);
int lengthToInt = Integer.parseInt(ln);
File file = new File(fn +".txt");
PrintStream stream = new PrintStream(file);
//System.out.println("File Has been Printed");
System.setOut(stream);
int[] result = getRandomNumbersWithNoDuplicates(rangeToInt, lengthToInt);
for(int i = 0; i < result.length; i++) {
Arrays.sort(result);
System.out.println(result[i] + " ");
}
System.out.println("Current Time in Millieseconds = " + System.currentTimeMillis());
System.out.println("\nNumber of element in the array are: " + result.length + "\n");
}// end of main
```
Don't call System.setOut. When you do that, you can no longer print to the console. Instead of System.out.println to write to the file, just... stream.println to write to the file. Then you can use System.out to print to the console.

My program compiles but still shows an error, java.util.NoSuchElementException

public static void cCommand(Scanner in) throws FileNotFoundException {
System.out.println();
System.out.print("Type an output file name: ");
String outFile = in.nextLine();
PrintStream ps = new PrintStream(new File("out.txt"));
Scanner input = new Scanner(new File("story.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner console = new Scanner(line);
while (input.hasNext()) {
String word = console.next();
if (word.startsWith("<") && word.endsWith(">")) {
char first = word.charAt(1);
String a = aeiou(first);
word = word.replace("<"," ");
word = word.replace(">"," ");
word = word.replace("-"," ");
System.out.print("Please type" + a + word + ": ");
String replace = in.next();
ps.print(" " + replace);
} else {
ps.print(" " + word);
}
}
}
} //end of cCommand method
this error pops up:
Type an output file name: Exception in thread "main" java.util.NoSuchElementException
NoSuchElementException error is because either
String replace = in.next();
or
String word = console.next();
still calling next but one of them no longer has a next element to provide. Make sure to call hasNext() first before calling next().

Java incorrect input [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);

Why System.out.println can't print out a string value (in my particular case)? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
My program should ask users to enter some value and evetually those value should be printed out depending on the menu option choosen (in my case it's 3). I have used System.out.println("Your name: " + name); to print out the name inserted by user, but unfortunately it can't print out the name. The line is just left empty. Why so? How can I fix it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userChoose;
String name = null;
int accNum = 0;
double initiateAmount = 0;
double newAmm = 0;
double depOrWith = 0;
System.out.println("WELCOME TO OUR BANK!\n\n"
+ "...................\n"
+ "...................\n\n"
+ "Choose your optiin:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View details\n"
+ "4. Deleting an account\n"//not used yet
+ "5. View all the accounts\n"//not used yet
+ "6. Quit\n\n");
System.out.println("*************\n"
+ "************");
while (true) {
userChoose = sc.nextInt();
if (userChoose == 1) {
System.out.println("Enter your full name:");
name = sc.nextLine();
sc.nextLine();
System.out.println("Choose an account number:");
accNum = sc.nextInt();
System.out.println("Enter an initiating amount:");
initiateAmount = sc.nextDouble();
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 2) {
System.out.println("Enter negative value to withdraw and positive to deposit");
depOrWith = sc.nextInt();
if (depOrWith < 0) {
initiateAmount = initiateAmount + depOrWith;
} else {
initiateAmount = initiateAmount + depOrWith;
}
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 3) {
System.out.println("Your name: " + name);
System.out.println("Your account number: " + accNum);
System.out.println("Your current balance: " + initiateAmount);
System.out.println("\n-----------\n"
+ "------------");
} else if (userChoose == 6) {
System.exit(0);
}
}
}
After selecting the option and pressing Enter, the Scanner is not reading the newline. Afterwards when name = sc.nextLine(); is called it will only read the new line following the selected option and name will be assigned the empty string. To solve this, simply add a call nextLine after reading the selected option, and remove the duplicate nextLine when reading the name:
while (true) {
userChoose = sc.nextInt();
sc.nextLine();
if (userChoose == 1) {
System.out.println("Enter your full name:");
name = sc.nextLine();
System.out.println("Choose an account number:");
...
Interchange the Blank nextLine() and the assigning one.
System.out.println("Enter your full name:");
sc.nextLine();
name = sc.nextLine();
System.out.println("Choose an account number:");
accNum = sc.nextInt();
name is null. If the user selects three you haven't actually assigned a value to the name variable yet, that only happens if they choose 1
When you select the option 3 you're not setting the name value which defaults to null, so it's printing Your name: null
You need to read and assign name value if you want something to be printed.

Suggestions with Strings from File

I am trying to read from a external file. I have successfully read from the file but now I have a little problem. The file contains around 88 verbs. The verbs are written in the file like this:
be was been
beat beat beaten
become became become
and so on...
What I need help with now is that I want a quiz like programe where only two random strings from the verb will come up and the user have to fill inn the one which is missing. Instead of the one missing, I want this("------"). My english is not so good so I hope you understand what I mean.
System.out.println("Welcome to the programe which will test you in english verbs!");
System.out.println("You can choose to be tested in up to 88.");
System.out.println("In the end of the programe you will get a percentage of total right answers.");
Scanner in = new Scanner(System.in);
System.out.println("Do you want to try??yes/no");
String a = in.nextLine();
if (a.equals("yes")) {
System.out.println("Please enter the name of the file you want to choose: ");
} else {
System.out.println("Programe is ended!");
}
String b = in.nextLine();
while(!b.equals("verb.txt")){
System.out.println("You entered wrong name, please try again!");
b = in.nextLine();
}
System.out.println("How many verbs do you want to be tested in?: ");
int totalVerb = in.nextInt();
in.nextLine();
String filename = "verb.txt";
File textFile = new File(filename);
Scanner input = new Scanner(textFile);
for (int i = 1; i <= totalVerb; i++){
String line = input.nextLine();
System.out.println(line);
System.out.println("Please fill inn the missing verb: ");
in.next();
}
System.out.println("Please enter your name: ");
in.next();
You can do something like this
import java.util.Scanner;
import java.io.*;
public class GuessVerb {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = in.nextLine();
File file = new File(fileName);
Scanner input = new Scanner(file);
String guess = null;
int correctCount = 0;
while(input.hasNextLine()) {
String line = input.nextLine(); // get the line
String[] tokens = line.split("\\s+"); // split it into 3 word
int randNum = (int)(Math.random() * 3); // get a random number 0, 1, 2
String newLine = null; // new line
int wordIndex = 0;
switch(randNum){ // case for random number
case 0: newLine = "------ " + tokens[1] + " " + tokens[2];
wordIndex = 0; break;
case 1: newLine = tokens[0] + " ------ " + tokens[2];
wordIndex = 1; break;
case 2: newLine = tokens[0] + " " + tokens[1] + " -------";
wordIndex = 2; break;
}
System.out.println(newLine);
System.out.println("Please fill inn the missing verb: ");
guess = in.nextLine();
if (guess.equals(tokens[wordIndex])){
correctCount++;
}
}
System.out.println("You got " + correctCount + " right");
}
}
Above is complete running program.

Categories