java.util.NoSuchElementException - java

Scanner sc=new Scanner(System.in);
int k=sc.nextInt();
sc.nextLine();
while(k-->0)
{
boolean t =false;
int n=sc.nextInt();
int l=sc.nextInt();
int i,j,m;
int a[]= new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<n-2;i++)
{
for(j=i+1;j<n-1;j++)
{
for(k=j+1;k<n;k++)
{
if((a[i]+a[j]+a[k])==l)
{
t=true;
break;
}
}
}
}
String f= t?"true":"false";
System.out.println(f);
}
sc.close();
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 Solution.main(Solution.java:17)
Sample Input
3
5 60
1 20 40 100 80
Sample output false
What did i tried?
if(sc.hasNextInt())
n=sc.nextInt();
if(sc.hasNextInt())
l=sc.nextInt();
I'm getting more duplicate outputs(i.e false) for the supposed hasNextInt() fix.

3
5 60
1 20 40 100 80
false
This is what I am getting after running your code. Your code is correct I guess. But you are not giving input to it.
java.util.NoSuchElementException is thrown when scanner can not find what you asked it to read.
Give exactly correct input.

It seems that you have closed the scanner before in your code. Do not close it & re-instantiate it in program, rather initialize it once at start of main program & close it at the end of main program.
Scanner is closed as its resources closed because it implements
Closeable interface.
Like in below example -
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println(System.in.available());
scanner.close();
scanner = new Scanner(System.in);
// System.out.println(System.in.available());
// If you uncomment above: It will give you java.io.IOException: Stream closed
String str = scanner.nextLine();
}
Derived this answer from post: java.util.NoSuchElementException - Scanner reading user input

put an iteration at the start, and check for condition like this:
do {
//Here the code
} while (i.hasNextInt());
and for the scanner error you should check if scanner has one like this
Scanner sc =new Scanner(System.in);
if (sc.hasNext()) {
//here the code
}

Related

Error in Scanner [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
Below is a program for palindrome. If it is palindrome it will print YES else NO.
I am unable to understand what's the difference in calling:
> int n=Integer.parseInt(in.nextLine());
> or int n=in.nextInt();
because both is doing the same work.
1st one is taking Stringas input then converting it into int
2nd one is taking directly int.
when the 1st one is taken there is no error.
But when 2nd one is taken it gets stored in n then it prints YES.(when debugged i found out that it gets stored in n but it skips the input string str and then it compares with str and s and prints YES).
So can anyone explain the logic behind this.
public class Test1 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//int n=Integer.parseInt(in.nextLine());
int n=in.nextInt();
while(n!=0){
String s="";
String str=in.nextLine();
for(int i=str.length()-1;i>=0;i--){
s=s+str.charAt(i);
}
if(str.equals(s) ){
System.out.println("YES");
}
else{
System.out.println("NO");
}
n--;
}
}
}
I guess that with Scanner you expect the String to be verified... in that case this line int n=in.nextInt(); will throw a java.util.InputMismatchException exception if the input is not a number.
The verification would be easier to achieve by using StringBuilder, like this:
Scanner in=new Scanner(System.in);
String original = in.nextLine();
StringBuilder reversa = new StringBuilder(original).reverse();
if (reversa.toString().equals(original)) {
System.out.println("YES");;
} else {
System.out.println("NO");;
}

How do I check whether user enters an integer between 2 numbers? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I want the user to input integers between 80 and 120 with no alphabets and other symbols. Here are my codes:
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//checking for integer input
while (!in.hasNextInt())
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
int userInput = in.nextInt();
//checking if it's within desired range
while (userInput<80 || userInput>120)
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
}
}
}
}
However, I'm facing an error. Is there a solution to this?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Array.main(Array.java:15)
Thank you! :)
EDIT: Thank you Tom, got the solution, but would like to try without "do"
Scanner in = new Scanner(System.in);
int userInput;
do {
System.out.println("Please enter integers between 80 and 120.");
while (!in.hasNextInt())
{
System.out.println("That's not an integer!");
in.next();
}
userInput = in.nextInt();
} while (userInput<81 || userInput >121);
System.out.println("Thank you, you have entered: " + userInput);
}
}
Your loop condition is wrong. You check something like "as long as there is no integer available from the input: read an integer". That is gonna fail
Also: You are calling nextInt twice. Don't do that. Remove the first call:
System.out.println("Please enter integers between 80 and 120.");
in.nextInt(); //REMOVE THIS LINE
int userInput = in.nextInt();
You are checking once if an int is available using hasNextInt, but then you read a value twice!
boolean continueOuter = true;
while (continueOuter)
{
System.out.println("Please enter integers between 80 and 120.");
String InputVal = in.next();
try {
int input = Integer.parseInt(InputVal);
//checking if it's within desired range
if(FirstInput>80 && FirstInput<120)
{
//no need to continue got the output
continueOuter = false;
}else{
System.out.println("Please enter integers between 80 and 120."); //need to continue didnt got the exact output
continueOuter = true;
}
} catch (Exception e) {
//not an int
System.out.println(InputVal);
continueOuter = true;
}
}
in this code i have created a boolean to check whether the program wants to continue or not. if the user has entered a valid value the program will stop
however you can change that as you wish. and you dont need two while loops i have changed the inner while loop to a if loop take a look at my code

Scanner Reading Data file Java.Util.NoSuchElementException: Null

I'm trying to write a class that will take in numbers from a file, but I keep running into this error when I run:
Java.util.NoSuchElementException: Null(in java.util.Scanner)
This is my code:
import java.util.*;
import java.io.*;
public class finalMain
{
public static void main (String args[]) throws IOException
{
int lineNumber = 0;
Scanner sc = new Scanner (new File ("Prog349f.txt"));
System.out.println("Student Quiz 1 Quiz2 MidTerm Final Final % Grade");
while(sc.hasNextLine())
{
lineNumber++;
sc.nextLine();
}
for(int i = 1; i <= 1; i++)
{
int quizOne = sc.nextInt();
int quizTwo = sc.nextInt();
int midterm = sc.nextInt();
int finalTest = sc.nextInt();
finalGrade studentNext = new finalGrade(sc.nextInt(),sc.nextInt(), sc.nextInt(),sc.nextInt(), i);
System.out.println(studentNext);
}
sc.close();
}
}
I'm thinking maybe I need to create two scanner objects, one for each line or something but I don't know how I would go about doing that.
You have misunderstood the usage of Scanner methods : sc.nextLine(); consumes and returns the line.
That means that you're currently reading the whole file with sc.nextLine();, discarding the result, and only then you try to read 4 ints, that can't be read since the Scanner is at the end of the file.
You should instead use one of these two methods :
If you're positive that each line of your file contains 4 ints separated by space (or any other specific character), and nothing more, you can then scan 4 ints while the scanner has a next line.
If there might be variations, or useless data, you should keep your hasNextLine() and nextLine() calls as they are, then use regex, split+indexing or another Scanner to retrieve the 4 ints from the line.

Java app is crashing on nextLine()

My application always crashs when it gets to scan.getLine() in main.
The error I get is "java.util.NoSuchElementException: No line found".
Here is the code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = new String();
int operation=0;
operation = getOperation();
System.out.print("Enter string:");
s = scan.nextLine(); // program crashes before I have the chance to input anything
System.out.println(s);
scan.close();
}
public static int getOperation(){ //get operation between 1-10
Scanner scan= new Scanner(System.in);
boolean input=true;
int op=0;
while (input){ // get correct input from the user
if (scan.hasNextInt())
{
op=scan.nextInt();
if (op < 1 || op > 10)
System.out.print("Please enter valid operation 1-10:");
else
input=false;
}
else
System.out.print("Please enter valid operation 1-10:");
scan.nextLine(); // to clear the buffer
}
scan.close();
return op;
}
The strange thing is that when I insert before I write getOperation function , and the entire getOperation was inside main, the application worked fine. Only after I moved the code to getOperation method , then the scan.nextLine() crashes, before I even have a change to enter anything in the console.
Try using this tiny code snippet
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
Scanner s2 = new Scanner(System.in);
s2.close();
s1.nextLine();
}
The close function closes the InputStream System.in
Since you are closing a scanner with scan.close(); in getOperation() a following call on another scanner with the same InputStream will cause the exception that you are running into.
You don't need the Scanner in main:
public static void main(String[] args) {
String s = new String();
System.out.print("Enter string:");
int operation = 0;
operation = getOperation();
s = "" + operation; // program crashes before I have the chance to input anything
System.out.println(s);
}
output:
Enter string:11
Please enter valid operation 1-10:1
1

Java read system input in while loop

here is a very simple code, in which i am trying to take input from keyboard in a loop. For every input, the loop is automatically running two extra times and taking the values 13 and 10, no matter what i give as input. can you please point out what i am doing wrong.
CODE:
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
boolean loop_cond=true;
int n=1;
while(loop_cond==true)
{
try
{
System.out.print("input : ");
n=br.read();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.print(n+"\n");
}
} // end Main
OUTPUT :
input : 6
54
input : 13
input : 10
input : 9
57
input : 13
input : 10
input : 1
49
input : 13
input : 10
input :
Those are probably \r\n values. Try Scanner to take in values.
Scanner input = new Scanner(System.in);
int i = input.nextInt();
Change
n=br.read();
to
n = Integer.parseInt(br.readLine());
But I would recommend you to use Scanner class to avoid the Integer conversion.

Categories