I made a program that asks for 3 integers to output type of triangle. Everything runs and compiled successfully, however, it seems the part where it asks the user to see if they want to loop it again, the online compiler outputs the error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at Assignment5.main(Assignment5.java:56)
import java.util.Scanner;
public class Assignment5 {
public static void main (String[]args)
{
for (int a = 0; a < Integer.MAX_VALUE; a++)
{
Scanner userInput = new Scanner(System.in);
Scanner answer = new Scanner(System.in);
int x,y,z;
System.out.println("Enter the sides of the triangle: ");
x = userInput.nextInt();
y = userInput.nextInt();
z = userInput.nextInt();
Tri isos = new Tri(x,y,z);
Tri equal = new Tri(x,y,z);
Tri scalene = new Tri(x,y,z);
// check the equilateral triangle
System.out.println(equal.toString() + " triangle:");
if (equal.is_isosceles())
System.out.println("\tIt is isosceles");
else
System.out.println("\tIt is not isosceles");
if (equal.is_equilateral())
System.out.println("\tIt is equilateral");
else
System.out.println("\tIt is not a equilateral");
if (equal.is_scalene())
System.out.println("\tIt is scalene");
else
System.out.println("\tIt is not scalene");
System.out.println("Would you like to enter values again? (y/n)" );
String input = answer.next(); //Exception is thrown from here
if (input.equals("y"))
{
System.out.println("ok");
}
else if(!input.equals("y"))
{
System.out.println("Ok, bye.");
break;
}
}
}
}
NoSuchElementException:
Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration.
You're getting this exception because Scanner#next doesn't read the new line character, which is the character when you press enter (\n), so in the next for iteration, you're trying to read it, which causes the exception.
One possible solution is to add answer.nextLine() right after answer.next() in order to swallow this extra \n.
Example of your code:
Iteration (a) | input for scanner | Data for scanner
--------------+-----------------------+-------------------
0 | "Hello" (And enter) | Hello
1 | \n | PROBLEM!
to me it seems that answer.next() does not actually have any value assigned to it
usually int name = answer.next() name is assigned what ever answer is. What i mean is that name cant be assigned a value because answer.next() doesn't have one.
At least this is my understanding. The alternative is the get rid of answer.next and use the other scanner.
actually an edit to this.
a scanner reads from files or the console. You have one scanner already (userInput) the second scanner isn't actually doing anything as well as it being an actual scanner, it doesn't have anything to read.
get rid of answer as a scanner, replace is with an int, String, double and have
int answer = userInput.nextInt();
or
double answer = userInput.nextDouble();
or
String answer = userInput.nextLine();
As you said the code runs for you but doesn't when compiled and executed on an online compiler. The answer scanner is exhausted because it doesn't have any elements.
It's embarrassing but i once got the same error when compiling my code on an online compiler, it turned out i wasn't supplying input beforehand to the input section and was expecting the online compiler to ask for the input.
Since you are using two scanners to get input from console, try using the scanner userInput to take the input from a file instead. (It may vary for different online compilers, but there will be an option to provide input from file)
Related
I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.
Here is a (slightly) augmented version of the source code example in the textbook:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// creates a scanner to obtain input from a command window
Scanner input = new Scanner(System.in);
int number1; // first number to add
int number2; // second number to add
int sum; // sum of 1 & 2
System.out.print("Enter First Integer: "); // prompt
number1 = input.nextInt(); // reads first number inputted by user
System.out.print("Enter Second Integer: "); // prompt 2
number2 = input.nextInt(); // reads second number from user
sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum
System.out.printf( "Sum is %d\n", sum ); // displays the sum on screen
} // end method main
} // end class Addition
I am getting the 'NoSuchElementException' error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:
I understand that this is probably due to something in the source code that is incompatible with the Scanner class from java.util, but I really can't get any further than this in terms of deducing what the problem is.
NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html
How about this :
if(input.hasNextInt() )
number1 = input.nextInt(); // if there is another number
else
number1 = 0; // nothing added in the input
You should use hasNextInt() before assigning value to variable.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.
I faced this Error with nextDouble(), when I input numbers such as 5.3, 23.8 ... I think that was from my PC depending on computer settings that use Arabic (23,33 instead 23.33), I fixed it with add:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
You must add input.close() at the end...
This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.
If I may, I solved this issue today by realizing that I had multiple functions that used an instance of a Scanner, each. So basically, try refactoring so that you have only one instance opened and then closed in the end - this should work.
For anyone using gradle's application plugin, you must wire it to the standard console in build.gradle(.kts) otherwise it will keep throwing the NoSuchElementException error if you try to use scanner.
For groovy:
run {
standardInput = System.in}
For gradle kotlin dsl:
tasks.withType<JavaExec>() {
standardInput = System.`in`}
Integer#nextInt throws NoSuchElementException - if input is exhausted
You should check if there is a next line with Integer#hasNextLine
if(sc.hasNextLine()){
number1=sc.nextInt();
}
I added a single static scanner (sc) at the top of my class and closed it (sc.close()) when coming out of the whole class wherever I used return statements. Again that's one instance of scanner as suggested by another answer, which should be static.
package com.example.com;
import java.util.Scanner;
public class someClass {
static Scanner sc = new Scanner(System.in);
//Whole world of methods using same sc.
//sc.close()); return;
}
Other than that you can add #SuppressWarnings("resource") on the top of the troubling method to make the warning go away. But be careful about resource leaks.
Im having some trouble with scanning user input in one of my first java programs. When I compile and run this, I am immediately prompted for input (i.e the command line stops and blinks). When I enter anything, the first line is printed, asking me to enter an integer. Then the second line is printed and I'm prompted to enter another value.
The output from this program is the first two values that I input. This is hard to explain, but it basically asks for 3 input values and only uses two.
import java.util.Scanner;
public class objects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer please...");
int input = sc.nextInt();
System.out.println("Enter your name please...");
String name = sc.nextLine();
System.out.println("The read values: " + input + ", " + name);
sc.close();
}
}
Put a System.out.flush() command after your println statements if you're reading from the console directly afterward
just use this:
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name please... ");
String name = sc.nextLine();
System.out.print ("Enter an integer please... ");
int input = sc.nextInt();
System.out.println ("The read values: " + input + ", " + name);
i just moved the integer below the name and it sorta fixed it. hahaha
When you introduce a number you press enter key, nextInt() uses the number but the enter (\n) remains buffered. After this if you call again nextInt(), Java tries to convert \n into a number giving you a NumberFormatException, but if you invoke nextLine() they read the enter as empty string
Here you have a better explanation and one solution
Can't use Scanner.nextInt() and Scanner.nextLine() together
It seems this is an error to do with my installation of VirtualBox. No matter what I try, the problem persists. Even if i try to only read ONE integer, it will ask me to input two values.
Thanks for everyone who tried to help, I learned a lot just trying to debug this.
New programmer here. This is probably a really basic question, but it's stumping me nevertheless.
What I'm trying to do is write a method that supplies only one integer input so I can use that input in my main program without having to mess around with non-integer inputs. However, even writing the method to do that in its own method seems to be problematic.
public static int goodInput () {
Scanner input = new Scanner (System.in); //construct scanner
boolean test = input.hasNextInt(); //set a sentinel value
while (test == false) { //enter a loop until I actually get an integer
System.out.println("Integers only please"); //tell user to give me an integer
test = input.hasNextInt(); //get new input, see if it's an integer
}
int finalInput = input.nextInt(); //once i have an integer, set it to a variable
input.close(); //closing scanner
return finalInput; //return my integer so I don't have to mess around with hasNextInt over there
}
This seems to be broken in multiple levels, but I'm not really sure why.
If I enter an integer value like 0 or 1 when I'm first asked for input, it should skip the loop entirely. But, instead, it enters the loop, and prints "Integers only please". Even worse, it doesn't actually ask for input while I'm in there, and just prints that line repeatedly.
I understand the latter problem is probably due to token issues, but I'm not necessarily sure how to solve them; closing and then reopening the scanner gets Eclipse to bug me over "duplicate objects", simply assigning the old input to a garbage String variable that is never used tells me that "No line was found" at runtime, and I'm not experienced enough to think of other ways to get new input.
Even once that's solved, I need to find some way to avoid entering the loop in the case of having an integer. I don't really understand why integer inputs inter the loop to begin with, so I'm not sure how this would be possible.
Please help? Sorry if this is an old question; tried looking at past questions but none of them seem to have the same problem that I have.
You were close: this works fine for me:
Scanner input = new Scanner(System.in); //construct scanner
while(!input.hasNextInt()) {
input.next(); // next input is not an int, so consume it and move on
}
int finalInput = input.nextInt();
input.close(); //closing scanner
System.out.println("finalInput: " + finalInput);
By calling input.next() in your while loop, you consume the non-integer content and try again, and again, until the next input is an int.
//while (test == false) { // Line #1
while (!test) { /* Better notation */ // Line #2
System.out.println("Integers only please"); // Line #3
test = input.hasNextInt(); // Line #4
} // Line #5
The problem is that in line #4 above, input.hasNextInt() only tests if an integer is inputted, and does not ask for a new integer. If the user inputs something other than an integer, hasNextInt() returns false and you cannot ask for nextInt(), because then an InputMismatchException is thrown, since the Scanner is still expecting an integer.
You must use next() instead of nextInt():
while (!input.hasNextInt()) {
input.next();
// That will 'consume' the result, but doesn't use it.
}
int result = input.nextInt();
input.close();
return result;
So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}