I'm getting an exception:
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 package1.smth.main(clas1.java:19)
When I remove the while(go)
part, everything is working fine. But I added it to be able to reset program, and now there is an exception. I also have a code for another similar program, where I added the same loop and it is working without this exception.
Can someone explain what's the problem?
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a : ");
a = input.nextDouble();
System.out.print("Enter b : ");
b = input.nextDouble();
System.out.print("Enter c : ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("first answer : " + (-b + d) / (2.0 * a));
System.out.println("second answer : " + (-b - d) / (2.0 * a));
} else if (discriminant == 0.0) {
System.out.println("first answer : " + (-b) / (2.0 * a));
System.out.println("second answer : " + (-b) / (2.0 * a));
} else {
System.out.println("no asnwers.");
input.close();
}
}
}
I've read everything I could find similar to my problem, and most answers came from this site. I tried to implement the given solutions to my code, and some didn't work, some I could not understand how to use because my code is different from the example in a question. I am total newbie, it is probably third program I wrote.
UPDATE: The final code I have. The only problem it shows, is "leak: scanner not closed".
package gg;
import java.util.Scanner;
public class hbh {
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("First answer: " + (-b + d) / (2.0*a));
System.out.println("Second answer: " + (-b - d) / (2.0*a));
}
else if (discriminant ==0.0) {
System.out.println("First answer: " + (-b) / (2.0*a));
System.out.println("Second answer: " + (-b) / (2.0*a));
}
else {
System.out.println("No answers");
input.nextLine();
}
}
}
}