java.util.NoSuchElementException in Java code - java

I get this exception:
Please provide width: 4
Please provide height: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at rr.fr.op.lab.prob1.Rectangle.scanner(Rectangle.java:51)
at rr.fr.op.lab.prob1.Rectangle.main(Rectangle.java:31)
My code is:
package rr.fr.op.lab.prob1;
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
if(args.length != 2 && args.length != 0){
System.err.println("Invalid number of arguments was provided.");
System.exit(1);
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double area = area(a,b);
double perimeter = perimeter(a,b);
System.out.println("You have specified a rectangle of width " + a + " and height "
+ b + ". Its area is " + area + " and its perimeter is " + perimeter);
}
double x,y,z;
if(args.length == 0){
System.out.printf("Please provide width: ");
x = scanner();
System.out.printf("Please provide height: ");
y = scanner();
}
}
private static double area(double a, double b){
return a*b;
}
private static double perimeter(double a, double b){
return 2*(a+b);
}
private static double scanner (){
Scanner sc = new Scanner (System.in);
double number = sc.nextDouble();
sc.close();
return number;
}
}
After that, I would like to use method trim() to delete whitespaces. Is that possible? And, I need isEmpty() method too. This code must calculate area and perimeter of rectangle. Inputs are form keyboar or command line.

You close the scanner after you use it. This also closes the underlying stream, System.in in this case, since it implements Closeable.
When you next create a scanner, System.in is already closed, so you can't read more elements from it.
Create a single scanner and reuse it multiple times.
It is considered a bad practice to close a stream if you didn't open it (or you have potentially leaked the reference).
There may be other code which relies upon the stream being open, so you closing it can lead to failures in that code. Failures remote from the cause like that are notoriously difficult to debug.
Unfortunately, it is very easy to close streams unintentionally, since classes like Scanner, BufferedInputStream etc close their underlying stream when they are closed.

You can basically pass scanner object to your method and close it after you are done with your scanning outside your scanner() method.
...
if (args.length == 0) {
Scanner sc = new Scanner(System.in);
System.out.printf("Please provide width: ");
x = scanner(sc);
System.out.printf("Please provide height: ");
y = scanner(sc);
sc.close();
}
...
private static double scanner(Scanner sc){
double number = sc.nextDouble();
return number;
}

Scanner sc = new Scanner(System.in);
System.out.println("Please provide width: ");
int number1 = 0;
try {
number1 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
System.out.println("Please provide height:");
int number2 = 0;
try {
number2 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}

Related

Fixing java.util.NoSuchElementException for Scanner [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 4 years ago.
How do I resolve the java.util.NoSuchElementException error? I call the scanner object 3 times, and the program will accept input the first two times. But on the third try, I immediately get the java.util.NoSuchElementException error. The name of the scanner object is stdInput.
I've tried creating a new scanner object just for the instance throwing this error, but I still get the same error, just from a different line in the code.
/**
* reddit url: https://www.reddit.com/r/dailyprogrammer/comments/pjbj8/easy_challenge_2/
*/
import java.util.Scanner;
public class challenge {
public static void main(String[] args) {
int choiceNum = 0;
boolean continueRunningProgram = true;
String repeatProgram = "";
Scanner stdInput = new Scanner (System.in);
do {
System.out.println("Are you solving for force (1), mass (2), or acceleration (3)?");
choiceNum = stdInput.nextInt();
if(isValidChoiceNum(choiceNum) == false) {
do {
System.out.println("The number " + choiceNum + " is an invalid choice. Please choose again.");
choiceNum = stdInput.nextInt();
} while(isValidChoiceNum(choiceNum) == false);
}
switch(choiceNum) {
case 1:
System.out.println("The force is " + solvingForForce());
break;
case 2:
System.out.println("The mass is " + solvingForMass());
break;
case 3:
System.out.println("The acceleration is " + solvingForAcceleration());
break;
}
System.out.println("Would you like to solve another problem involving force, mass, and acceleration (Y/N)?");
repeatProgram = stdInput.next();
if(isValidChoiceChar(repeatProgram) == false) {
do {
System.out.println("The letter " + repeatProgram + " is an invalid choice. Please choose again.");
repeatProgram = stdInput.next();
} while(isValidChoiceChar(repeatProgram) == false);
}
if(repeatProgram.compareTo("Y") == 0) {
continueRunningProgram = true;
} else {
continueRunningProgram = false;
}
} while(continueRunningProgram == true);
stdInput.close();
} // end of main method
public static boolean isValidChoiceNum(int c) {
if(c < 1 || c > 3 ) {
return false;
} else {
return true;
}
}
public static boolean isValidChoiceChar(String c) {
if(c.compareTo("Y") == 0 || c.compareTo("N") == 0) {
return true;
} else {
return false;
}
}
public static double solvingForForce() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for mass.");
double m = stdInput2.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = stdInput2.nextDouble();
stdInput2.close();
return m * a;
}
public static double solvingForMass() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for force.");
double f = stdInput2.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = stdInput2.nextDouble();
stdInput2.close();
return f / a;
}
public static double solvingForAcceleration() {
Scanner stdInput2 = new Scanner (System.in);
System.out.println("Please enter a value for force.");
double f = stdInput2.nextDouble();
System.out.println("Please enter a value for mass.");
double m = stdInput2.nextDouble();
stdInput2.close();
return f * m;
}
} // end of class
Stop the madness of closing a Scanner linked to System.in! It will close the underlying stream (System.in), causing any other attempt to read from that Stream to throw an exception.
Yes you will get a warning, but it is safe to ignore that warning, or you can add
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
To avoid it.
Remember, if you didn't open a resource, you shouldn't close it. Let the JVM close it when it terminates the program.
This also includes creating a Scanner(System.in) inside a try with resources block:
try(Scanner in = new Scanner(System.in)){
//Code...
}
This will implicitly close the stream at the end of the block.
From the Java tutorials:
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Also you have several Scanner objects reading from System.in, which is bad practice. I would pass them to your methods as a parameter:
public static double solvingForMass(Scanner in) {
System.out.println("Please enter a value for force.");
double f = in.nextDouble();
System.out.println("Please enter a value for acceleration.");
double a = in.nextDouble();
return f / a;
}
Also just a note that if you are ever doing the structure of:
if(someBool)
return true;
else
return false;
It can be simplified to just
return someBool
So your isValidChoice() method can be simplified to:
public static boolean isValidChoiceChar(String c) {
return c.compareTo("Y") == 0 || c.compareTo("N") == 0;
}
Although note you can use the equals() and equalsIgnoreCase()methods to compareString`'s

Ask to insert numbers only

So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}

Second scanner is ignoring input

I have written Java code that has Scanners. What it is supposed to do is get 2 inputs and then do the math. The problem is that the second scanner doesn't work properly. It automatically does the else statement without asking for input.
package stuff;
import java.util.Scanner;
public class Diagonal {
public static void main(String[] args) {
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
double c = a + b;
System.out.println(Math.sqrt(c));
}
static double getWidth() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the width.");
double width;
if(scan.hasNextDouble()) {
width = scan.nextDouble();
}
else {
System.out.println("Sorry, there was an error!");
width = 0;
}
scan.close();
return width;
}
static double getHeight() {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter the height");
double height;
if(scan2.hasNextDouble()) {
height = scan2.nextDouble();
}
else {
System.out.println("Sorry, there was an error!");
height = 0;
}
scan2.close();
return height;
}
}
You can not do this:
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
because getHeight() and getWidth() are methods that close the scanner, which is closing the System.in stream too...
so your 2 condition scan.hasNextDouble() is never met!
Solution:
use 1 scanner instance and close it when you are done reading inputs
You can't reopen a standard input stream once you close it. Your getHeight() method closes it so your getWidth() method cannot open it again.
Open a standard input stream once for your program and don't close it until you're done reading all user inputs.
You cannot reopen standard input stream once it is closed. so in our code remove Scanner objects from both methods and initialize it in the 'main' function once. like this and use the 'scan' object in both functions.
`static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
double a = Math.pow(getHeight(), 2);
System.out.println(a);
double b = Math.pow(getWidth(), 2);
double c = a + b;
System.out.println(Math.sqrt(c));
scan.close();
}`

How to repeat execution until user input is correct in Java? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
im beginner in java programing, have task need to be completed and looking for some useful tips. writing program which requires from user correct Float input, if input is incorrect, program gives another chance until correct input, my problem is next, when i enter incorrect input it runs non stop,, any ideas?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
float f = 0;
int x = 1;
do {
try {
System.out.print("Enter an float:");
f = in.nextFloat();
x =2;
} catch (InputMismatchException e) {
System.err.println("Incorrect entry.");
}
System.out.println("Your entry is:" + f);
}
while(x==1);
}
Do this and you will get the output you want from your program
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
float f = 0;
int x = 1;
do {
try {
System.out.print("Enter an float:");
f = in.nextFloat();
x = 2;
} catch (InputMismatchException e) {
System.err.println("Incorrect entry.");
in.next();
}
} while (x == 1);
System.out.println("Your entry is:" + f);
}
You just need to add in.next() in catch block to continue the process.
As an alternative to the accepted answer, you may want to :
1) Check that the next token is a float hasNextFloat()
2) If it isn't, swallow the whole line nextLine()
Scanner in = new Scanner(System.in);
float f = 0;
String entry;
int x = 1;
do {
System.out.print("Enter an float:");
if (in.hasNextFloat()) {
f = in.nextFloat();
entry = Float.toString(f);
x = 2;
} else {
entry = in.nextLine();
System.err.println("Incorrect entry.");
}
System.out.println("Your entry is: " + entry);
} while (x == 1);
This has the advantage of getting rid, of wrong input line having multiple tokens (e.g : "aa bb cc").

Using a While Loop in Java

import java.io.*;
import java.util.*;
public class volumeConeD
{//class
public static void main (String [] args)
{//main
Scanner keyBoard = new Scanner(System.in);//input for keyBoard
//variables
double volume;
double radius;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{//begin of try
while(r == true){
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println ();
System.out.println ();
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble ();
//math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf ("Volume = " + volume);
}//end of try
catch (Exception Error){
System.out.println("You entered wrong data");
}
System.out.println ();
System.out.print("Does the user wish to try again?");
System.out.println ();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}//end of while
}//end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}//end of program
this is my first time posting on this forum, so please excuse how ask...here goes... all i am trying to do with this is repeat this problem under user control using a sentinel method(while loop). I had it almost working earlier but i kept getting errors about how i defined "r". Now i get errors about my catch try blocks. please help.
volumeConeD.java:35: error: 'catch' without 'try'
catch (Exception Error){
^
volumeConeD.java:35: error: ')' expected
catch (Exception Error){
^
volumeConeD.java:35: error: not a statement
catch (Exception Error){
^
volumeConeD.java:35: error: ';' expected
catch (Exception Error){
^
volumeConeD.java:19: error: 'try' without 'catch', 'finally' or resource declarations
try
^
5
You placed your try { outside the while loop, but the corresponding catch is within the while loop. But must be either outside the loop or inside the loop, together.
Try placing the try { lines inside the while loop.
Additionally, it looks like these lines won't work either:
radius = getRadius(radius);//call to method
radius = keyBoard.nextDouble ();
All getRadius does is print out a prompt and return the passed in parameter, radius. But radius hasn't been initialized yet. But it looks like nothing is done with it yet anyway. Rename the method something like promptForRadius, and it doesn't need to take in a parameter or return anything.
public static void promptForRadius()
{
System.out.print("Enter Radius Squared Number ");
}
Then when calling it:
promptForRadius();
// Then you can call this line (unchanged)
radius = keyBoard.nextDouble();
Where your comment says // end of try it should really say // end of while and vice versa.
I have reformatted the code. Braces for try/catch block cannot end before while loop braces. Also you have to initialize variables before using them (e.g,. radius). Eclipse like IDE will be helpful to format and identify compilation errors. BTW I have not checked the logical correctness of the code but more of compilations and syntax issues
import java.util.Scanner;
public class volumeConeD
{
public static void main(String[] args)
{
Scanner keyBoard = new Scanner(System.in);// input for keyBoard
// variables
double volume;
double radius = 0.0;
double hieght;
double oneThird = 0.3333;
double pie = 3.14;
double yes = 1.0;
boolean r = true;
try
{// begin of try
while (r == true)
{
System.out.print("Volume of a Cone... V=1/3(3.14)r^2(h)");
System.out.println();
System.out.println();
radius = getRadius(radius);// call to method
radius = keyBoard.nextDouble();
System.out.print("Enter a Height ");
hieght = keyBoard.nextDouble();
// math
volume = oneThird * pie * radius * radius * hieght;
System.out.printf("Volume = " + volume);
System.out.println();
System.out.print("Does the user wish to try again?");
System.out.println();
System.out.print("Enter 1 to go again OR any other key to end.");
yes = keyBoard.nextDouble();
}// end of while
}// end of try
catch (Exception Error)
{
System.out.println("You entered wrong data");
}
}// end of main
public static double getRadius(double mRadius)
{
System.out.print("Enter Radius Squared Number ");
return mRadius;
}
}// end of program
This seems to be your problem
try
{
while (...)
{
int blammo;
try
{
... code
blammo = 9;
}
catch ...
{
// catching here means that the while loop will continue looping.
}
System.out.println("Blammo: " + blammo); // This results in the error: variable
// blammo might not have been initialized. This is because the assignment
// "blammo = 9" is inside the try block and if an exception was thrown before
// the assignment then it (the assignment) will never execute and blammo will
// be uninitialized.
} // end of while loop
} // end of outter try
catch ...
{
// catching here means that the exception exits the while loop.
}
You use a catch, but it's not matching with the try...
oneThird variable can be set as 1 / 3 (more precision).
Same for PI, the Math library already has a PI definition.
The function getRadius is useless, you should take it off, or maybe replace it by a function which asks the user to enter a double number.
import java.util.Scanner;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double volume, radius, height, oneThird = (1.0 / 3);
int continueExecution = 1;
try {
while (continueExecution == 1) { // same as r == true (redundant)
System.out.println("Volume of a Cone... V=1/3(3.14)r^2(h)\n\n"); // '\n' is the newline character
radius = getDoubleValue(sc, "Enter radius : ");
height = getDoubleValue(sc, "Enter height : ");
volume = oneThird * Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume = " + volume + "\nEnter 1 to start again, or another number to exit: ");
continueExecution = sc.nextInt();
}
} catch (Exception e) { // Pokemon exception handling !
System.err.println(e.getMessage());
}
}
public static double getDoubleValue(Scanner sc, String msg) {
System.out.print(msg);
return sc.nextDouble();
}

Categories