JAVA Exception in thread main java.util.no such element - java

I encountered an error when executing my program.
I execute my program and fed data in an input file.
Contents of the input file
LIMIT
2
ADD 30 60
MUL -60 60
I got an exception error as follows.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Test.doLimit(Test.java:41)
at Test.checkResult(Test.java:24)
at Test.main(Test.java:15)
I googled and I believed that String input = sc.next(); inside the for loop should be causing the error.
May I know how to resolve this error?
My code is as attached below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
checkResult(input);
}
public static void checkResult(String input)
{
if(input.equals("LIMIT"))
{
//do stuff
doLimit();
}
else if(input.equals("SENT"))
{
//do stuff
}
else
{
//do stuff
}
}
public static void doLimit()
{
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int x,y;
for(int i = 0; i < numOfInput; i++)
{
String input = sc.next();
x = sc.nextInt();
y = sc.nextInt();
if(input.equals("ADD"))
{
//add
}
else if(input.equals("SUB"))
{
//sub
}
else
{
//multiple
}
}
}

You should check if there is more input. You can see in the stack trace that nextInt is involved and if you look at the SDK you would see that this exception is thrown when
input is exausted.
anyway you problem is here :
int numOfInput = sc.nextInt();
so make sure you have valid input before asking for it :
if (sc.hasNextInt()) {
.
.
.
}

The default delimiter of the scanner is the whitespace. However, you plan to use as input for the first 2 lines the new line as delimiter and then either whitespace and new line, as it comes first. Maybe that is the problem. Try writing everything on one line, whitespace separated.

If you are sending the data through the input file, you have to provide that file in the Scanner() constructor.
What you have currently done is provided System.in.
EDIT :
Also, you have to open the Scanner on the file just once and use it throughout. In this case,
1) You are opening the scanner and reading the first line.
2) Then in the doLimit function, you again open the scanner and read the first line of the input file which is not an integer.
Hence, the error.

Related

How to solve NoSuchElement in java?

It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}

NoSuchElementException : No line found

I am working on a simple project, I took it from a website that gives some challenge to improve my coding skill in java.
import java.util.Scanner;
public class Test1 {
public void test() {
Scanner in = new Scanner(System.in);
System.out.println("enter something :");
String str = in.nextLine();
StringBuilder sb = new StringBuilder(str);
if (str.isEmpty()) {
System.out.println("you should write something");
}
if(str.length()<=30){
System.out.println("reverse : "+sb.reverse());
}else {
System.out.println("Error");
}
System.out.println("----------------------");
}
public static void main(String[] args) {
Test1 c = new Test1 ();
for (int i = 1; i <= 10 ; i++) {
System.out.println("case number : " +i);
c.test();
}
}
}
case number : 1
enter something : ayoub
reverse : buoya
----------------------
...loop continue ..
My code works like I want in terminal of eclipse, but when I put it into the "code editor" of the web site, this last one gives me a runtime error that says:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Test1.test(Test1.java:10)
at Test1.main(Test1.java:31)
I tried to search on StackOverflow for some solutions but I didn't find it.
You are probably using an online java code editor/compiler which does not have an stdin input.
As stated by arcy, you are probably using an IDE with a built-in console window which allows you to pass standard inputs to your program.
The following online editor will allow you to add inputs.
You should take care of the way you are using the nextLine method of Scanner:
The exception you are getting is the result of the scanner not getting any inputs, as can be seen here. I suggest you refactor your loop on the scanner using the method hasNextLine of Scanner.

Runtime Error Using Scanner class [duplicate]

I got an run time exception in my program while I am reading a file through a Scanner.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Day1.ReadFile.read(ReadFile.java:49)
at Day1.ParseTree.main(ParseTree.java:17)
My code is:
while((str=sc.nextLine())!=null){
i=0;
if(str.equals("Locations"))
{
size=4;
t=3;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Professions"))
{
size=3;
t=2;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Individuals"))
{
size=4;
t=4;
str=sc.nextLine();
str=sc.nextLine();
}
int j=0;
String loc[]=new String[size];
while(j<size){
beg=0;
end=str.indexOf(',');
if(end!=-1){
tmp=str.substring(beg, end);
beg=end+2;
}
if(end==-1)
{
tmp=str.substring(beg);
}
if(beg<str.length())
str=str.substring(beg);
loc[i]=tmp;
i++;
if(i==size ){
if(t==3)
{
location.add(loc);
}
if(t==2)
{
profession.add(loc);
}
if(t==4)
{
individual.add(loc);
}
i=0;
}
j++;
System.out.print("\n");
}
with Scanner you need to check if there is a next line with hasNextLine()
so the loop becomes
while(sc.hasNextLine()){
str=sc.nextLine();
//...
}
it's readers that return null on EOF
ofcourse in this piece of code this is dependent on whether the input is properly formatted
I also encounter with that problem.
In my case the problem was that i closed the scanner inside one of the funcs..
public class Main
{
public static void main(String[] args)
{
Scanner menu = new Scanner(System.in);
boolean exit = new Boolean(false);
while(!exit){
String choose = menu.nextLine();
Part1 t=new Part1()
t.start();
System.out.println("Noooooo Come back!!!"+choose);
}
menu.close();
}
}
public class Part1 extends Thread
{
public void run()
{
Scanner s = new Scanner(System.in);
String st = s.nextLine();
System.out.print("bllaaaaaaa\n"+st);
s.close();
}
}
The code above made the same exaption, the solution was to close the scanner only once at the main.
You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
Need to use top comment but also pay attention to nextLine(). To eliminate this error only call
sc.nextLine()
Once from inside your while loop
while (sc.hasNextLine()) {sc.nextLine()...}
You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.
Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.
I ran into this problem, my structure was:
1 - System
2 - Registration <-> 3 - validate
I was closing Scanner on each of the 3 steps. I started to close the Scanner only in system and it solved.

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

How to input a specific number of words in java?

I'm supposed to input an array of strings in java according to the following specification:
Input:A text containing K English words (where K <= 5000), with spaces and punctuation marks
My approach is to use an array of strings, each string containing a word and taking input using java.util.Scanner.next() inside a loop.
My problem is how to stop taking inputs when the user hits enter. Any idea?
Use a Scanner. Read the lines that the user enters. If the user enters an empty line then exit the loop:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
while (true) {
final String read = scanner.nextLine();
if ("".equals(read)) {
break;
}
System.out.println(read);
}
}
You could use two Scanner objects to handle this like so:
Scanner inScan = new Scanner(System.in);
String line = sinScan.nextLine();
while (line.length() > 0) {
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()) {
String word = lineScan.next();
// process this word.
}
line = inScan.nextLine();
}
// loop should exit when the user enters a blank line.

Categories