Java parsing strings Error: Exception in thread "main" java.util.NoSuchElementException - java

Why do I get an exception error when trying to run this program? What does it mean and how can I fix it? Is it because I am using nextline? I get no error when running this in IntelliJ but when I run it in Zybooks (online coding lessons with assignments) I get the error.
My error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at ParseStrings.main(ParseStrings.java:40)
Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!userInput.equals("q")) {
while (userInput.contains(",") == false) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string:");
userInput = scnr.nextLine();
}
String[] myArray = userInput.split(",");
System.out.println("First word: " + myArray[0]);
System.out.println("Second word: " + myArray[1]);
//get the next input
System.out.println("Enter input string:");
userInput = scnr.nextLine();
}
}
}

The issue is when you assign a value to userInput variable so you aren't be able to call it again in loop while so you need call it from scanner, let me add this example:
while (!(userInput = scnr.nextLine()).equals("q")) {
....
}

Related

I keep getting this error java.util.NoSuchElementException

I am getting a NoSuchElementException which is probably due to Scanner and I get it after I add a student and go back to the menu.
My main method:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static ArrayList<Student> students = new ArrayList<>();
static Scanner scan = new Scanner(System.in);
static Student s = new Student();
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println(" ***Students Manage***\n");
System.out.println("1 - Insert a student");
System.out.println("2 - Display students");
System.out.println("3 - Remove student\n");
option();
}
public static void option() {
int option;
do {
System.out.print("Choose an option: ");
option = scan.nextInt();
}while(option < 1 || option > 3);
switch(option) {
case 1:
s.addStudent();
students.add(s);
break;
case 2:
showAllStudents();
}
menu();
}
private static void showAllStudents() {
for(int i = 0; i < students.size(); i++) {
students.get(i).toString();
}
}
}
My Student method:
import java.time.LocalDate;
import java.util.Scanner;
public class Student {
String name;
int studentNumber;
static int count = 1;
int yearNumber;
public Student() {
}
public void addStudent() {
Scanner scan = new Scanner(System.in);
LocalDate year = LocalDate.now();
yearNumber = year.getYear();
studentNumber = count++;
studentNumber += yearNumber * 10000;
System.out.print("Enter the student name: ");
name = scan.nextLine();
if(name == null || name.trim().equals("") || !name.contains(" "))
{
do{
if(name.trim().equals("")){
System.out.print("Please enter a valid name.\nEnter your name: ");
} else if(!name.contains(" ")) {
System.out.print("You should write at least 2 names(name and surname).\nEnter your name: ");
}
name = scan.nextLine();
}while(name == null || name.trim().equals("") || !name.contains(" "));
}
scan.close();
System.out.println("The student "+name+" was added to the student list "
+ "and his/her student number is "+studentNumber);
}
#Override
public String toString(){
return name+" - "+studentNumber;
}
}
The error that I'm getting:
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 StudentSchool.Main.option(Main.java:29)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.option(Main.java:40)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.option(Main.java:40)
at StudentSchool.Main.menu(Main.java:21)
at StudentSchool.Main.main(Main.java:13)
You have two problems in how you're using Scanner. The first is that you are opening a second Scanner on System.in while you have one already open and reading from it. This produces strange results due to buffering. You should create and use only a single Scanner object that you never close. You can do this by passing the Scanner you create in your main() method into your addStudent() method so that it can use that same Scanner instead of creating and later closing a new one. So...
public void addStudent(Scanner scan) {
// Scanner scan = new Scanner(System.in);
....
// scan.close();
....
public static void option() {
....
s.addStudent(scan);
...
When you do this, a second problem will arise. When you mix calls to nextInt and nextLine on a Scanner object, you run into a problem where nextInt only reads the numeric digits from the input stream, but leaves the newline character produce by the user hitting Return. When you then call readLine, it reads that newline that's already on the input stream, so instead of waiting for your input, it reads an empty line as the next result. To avoid this problem, you should add an extra call to readLine right after you call readInt to consume this stray newline character. So...
System.out.print("Choose an option: ");
option = scan.nextInt();
scan.nextLine();
Making these two changes should cause your program to behave as you desire.

Cannot take input with Scanner [duplicate]

This question already has an answer here:
Closing a Scanner throws java.util.NoSuchElementException
(1 answer)
Closed 2 years ago.
I just can't read with scanner. I read a lot of other posts but i just cannot understand what in the world is wrong with this. I have tried with Buffer read but it gives error as well.
I just can't figure it out. What should i do?
This is the error:
Start : 1
Exit : 2
=> 1
Enter your name
=>
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at pcGame/pkg.GameLogic.characterCreation(GameLogic.java:28)
at pcGame/pkg.GameLogic.main(GameLogic.java:41)
This is the code:
package pkg;
import java.util.Scanner;
public final class GameLogic {
public void gameMenu() {
System.out.print("Start : 1\nExit : 2\n=> ");
int opt = 1;
Scanner input = new Scanner(System.in);
opt = input.nextInt();
switch(opt) {
case 1:
input.close();
return;
case 2:
System.exit(0);
}
input.close();
}
public void characterCreation() {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name\n=> ");
String name = input.nextLine();
System.out.println("Enter your \n=> ");
String story = input.nextLine();
//Player.initialize("name", "story"); //Initializes Player
input.close();
}
public static void main(String[] args) {
GameLogic game = new GameLogic();
game.gameMenu();
game.characterCreation();
while(true) {
//Game Happens
break;
}
}
}
Just try to remove input.close(); statements

homework parsing strings: removing comma from string (java zybooks)

I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];

Scanner Issue with Java String Parsing

Feel like I'm missing something really basic here, but my brain is fried right now. Goal is to parse strings with a comma, gets through one loop and throws before the next line. Pretty sure it has something to do with userInput = scan.nextLine();
import java.util.Scanner;
public class ParseStrings
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String userInput = "";
boolean finished = false;
while (!finished)
{
System.out.print("Enter input string: \n");
userInput = scan.nextLine();
if (userInput.equals("q"))
{
System.out.println("First word: " + userInput);
finished = true;
} else
{
String[] userArray = userInput.split(",");
System.out.println("First word: " + userArray[0]);
System.out.println("Second word: " + userArray[1]);
System.out.println();
}
}
return;
}
}
Throwing:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ParseStrings.main(ParseStrings.java:12)
Thank you in advance

Keep getting "Exception in thread "main" java.util.InputMismatchException: For input string"

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

Categories

Resources