This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
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();
}
}
}
}
You should delete
input.close();
When you close the System.in once, you can not use it again after having closing it.
I can not find the source but here is a proof that this is causing the problem.
Try running the following code and you'll get the exact same exception.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.close();
Scanner other = new Scanner(System.in);
other.nextDouble();
}
When you call, input.close() it not only closes your scanner but closes your System.in. Now you still keep iterating over the loop even when scanner is closed (and keep scanning values) which causes excpetion.
UPDATE
Your code seems to go in a infinite loop because you do not break from the loop neither do you update the value of go which at some point might terminate the loop.
Thus, the scanner will keep reading values until all the inputs are exhausted and eventually throw java.util.NoSuchElementException exception (when all the inputs are exhausted).
Related
My program is not close to being finished, but I am stuck because the compiler gives me an error message "cannot find symbol - method years(double)" in the depreciatonTable method the variable years.
-I am sure it is very obvious, but I cannot seem to figure out why the compiler comes up with an error.
import java.util.Scanner;
public class Problem1
{
public static void main(String args[])
{
double AcquisVal, SalvageVal, years;
Scanner scan = new Scanner(System.in);
Problem1 val = new Problem1();
System.out.println("Enter the Acquisition Value: ") ;
AcquisVal = scan.nextDouble();
System.out.println("Enter the Salvage Value: ");
SalvageVal = scan.nextDouble();
System.out.println("Enter the years of useful life(in whole years): ");
years = scan.nextDouble();
if (AcquisVal < 0)
{
System.out.println("Acquisition value cannot be negative");
}
else if (years < 1){
System.out.println("Years of useful life must be greater than zero");
}
else if (SalvageVal < 0){
System.out.println("Salvage value cannot be negative");
}
else
val.depreciationtable(AcquisVal, SalvageVal, years);
}
public double depreciationtable(double years, double AcquisVal, double SalvageVal)
{
double depreciation, fraction, annDepreciation, AccDepreciation, BookValue;
while (years > 0)
{
fraction = years / (years (years + 1)/ 2);
years--;
}
depreciation = (AcquisVal - SalvageVal) * fraction;
return depreciation;
}
}
There is something wrong in your logic at
fraction = years / (years (years + 1)/ 2). The years (years + 1) part is logically wrong.
Also, look at the Java Naming conventions to use correct variable/method names.
I am making a Pythagorean theorem program to solve for a missing side, and if the user enters 0 as the value that means that that is the missing side to solve for. My program is not getting the correct answer. Your help is greatly appreciated.
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the value of a");
a=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of b");
b=scan.nextDouble();
scan.nextLine();
System.out.println("Enter the value of c");
c=scan.nextDouble();
scan.nextLine();
if(a==0)
{
newb=Math.pow(b, b);
newc=Math.pow(c, c);
double result=newc-newb;
newa=Math.sqrt(result);
}
System.out.println("The value of a is " + newa);
}
}
Okay! So the problem I see with this Java code would be that it doesn't necessarily follow the actual pythagorean theorem. I see that if (A==0) then execute the actual equation, but you must remember that variable A isn't the hypotenuse of the triangle!
A^2 + B^2 = C^2 (C being the hypotenuse) If you want to make it so that it finds any part of the triangle you must remember to derive the equation so that you can find the missing side! Such as, you have side A and C but you want to find side B, the equation would then be B^2 = C^2-A^2.
Last of all, I see you have newb=Math.pow(b, b); that would power your variable to itself! Even the the powers are only 2, so it would be newb=Math.pow(b, 2);
TIP! Remember to capitalize the second word in a variable name like numa to numA
/* REMEMBER THAT A NUMBER MUST NEVER BE GREAT THAN C UNLESS IT IS THE UNKNOWN OR YOU WILL ENCOUNTER A NONREAL NUMBER BECAUSE YOU CAN'T SQUARE ROOT A NEGATIVE NUMBER*/
import java.util.Scanner;
import java.lang.Math;
public class pythagTheorem {
static double a;
static double b;
static double c;
static double newa;
static double newb;
static double newc;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a ZERO for the unknown side!");
System.out.println("Enter the value of side A :: ");
a = scan.nextDouble();
System.out.println("Enter the value of B :: ");
b = scan.nextDouble();
System.out.println("Enter the value of C :: ");
c = scan.nextDouble();
if (a == 0) {
newc = Math.pow(c, 2);
newb = Math.pow(b, 2);
newa = Math.sqrt(newc - newb);
System.out.println("Your missing side is :: " + newa);
}
else if(b == 0){
newc = Math.pow(c, 2);
newa = Math.pow(a, 2);
newb = Math.sqrt(newc - newa);
System.out.println("Your missing side is :: " + newb);
}
else if(c == 0){
newa = Math.pow(a, 2);
newb = Math.pow(b, 2);
newc = Math.sqrt(newa + newb);
System.out.println("Your missing side is :: " + newc);
}
else
System.out.println("Sorry! There is an error!");
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
So I have this code:
public class Subjects {
String name;
int period;
char grade;
public void period()
{
System.out.println("I have " + this.name + " during period " + this.period + ".");
}
public void study()
{
if (this.grade == 'B')
{
System.out.println("I study for " + this.name + ", so I get a B!");
}
else if (this.grade == 'A')
{
System.out.println("I study for " + this.name + ", so I get an A!");
}
else
{
System.out.println("I don't study for " + this.name + ", so I get a " + this.grade +". :(");
}
}
}
And this test class:
import java.util.Scanner;
public class SubjectsTest {
public static void main (String [] args)
{
Scanner kboard = new Scanner(System.in);
Subjects[] classes;
System.out.print ("How many classes do you have? ");
int x = kboard.nextInt();
int y;
classes = new Subjects[x];
for (int b = 0; b < x; b++)
{
classes[b] = new Subjects();
}
for (int a = 0; a < x; a++)
{
y = a + 1;
System.out.println("Period " + y );
System.out.println ("Enter the subject name: ");
classes[a].name = kboard.nextLine();
System.out.println ("Enter your class period: ");
classes[a].period = kboard.nextInt();
System.out.println ("Enter your grade in the class: ");
classes[a].grade = kboard.next().charAt(0);
}
for (int i = 0; i < x; i++)
{
classes[i].period();
classes[i].study();
}
}
}
What should happen is the user puts in the number of classes they have (e.g. 8) and then puts in the name, period and their grade for each one. Then at the end, it prints 2 statements for each class.
However, when I run the program (in Eclipse), after it asks How many classes do you have? and the user answers, the system prints out the next two questions without waiting for an answer to the first. My error message looks like this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at SubjectsTest.main(SubjectsTest.java:27)
Why does it do this? How can I fix it? I'm new to Java, so any help would be much appreciated!
You should put a kboard.nextLine(); after your kboard.nextInt(); call that gets the number of classes.
This will read in the rest of the kboard.nextInt(); line and allow reading in your subject name to work properly. Currently, your kboard.nextLine(); to read in the subject name is reading in the remainder of your input for the number of classes. So when you're trying to read in the subject, it's actually waiting for the int for period and giving you that exception.
EDIT: Sorry for all the edits, the accepted answer for this question might make a little more sense: Using scanner.nextLine()
The goal is to create a program that takes a quadratic equation in quadratic form and solve it. Is there a different way to go about doing so other than StringTokenizer? Or is it possible to isolate just ^2 in StringTokenizer rather than ^ and 2 like it is doing now? I realized that using the way I wrote it, it will not allow equations to use 2 at all.
This question requires me to not take individual coefficients, but rather the entire equation itself.
Sample run: ”java SolveEquation2 1.5625x∧2+2.5x+1=0”. For this input the output should be: ”x=-0.8”
import java.util.Scanner;
import java.util.StringTokenizer;
class SolveEquation2 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Input a quadratic");
String equation = scan.nextLine();
StringTokenizer st = new StringTokenizer(equation, "x^2+-");
String a,b,c;
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
double c1 = Double.parseDouble(c);
double x = (b1 * b1) - (4 * a1 * c1);
double var1 = (-b1 + Math.sqrt(x)) / (2*a1);
double var2 = (-b1 - Math.sqrt(x)) / (2*a1);
if (x == 0){
System.out.println("x = " + var1);
}
if (x > 0){
System.out.println("x1 = " + var1);
System.out.println("x2 = " + var2);
}
if (x < 0){
System.out.println("No Solution");
}
}
}
You want to use regular expressions to parse the command line input.
It seems that what you're trying to do has been done many times before.
See here
I'm working on a Java assignment and whenever I insert a decimal into my scanner, the code returns errors. I went far enough to realize that it wasn't because the number was a decimal, but because whenever any character that is not a number is entered this error is returned.
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 population.main(population.java:14)
If anyone can help me get decimals to work that would be cool, here is my bad code.
import java.util.Scanner;
public class population {
public static void main(String[] args) {
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
}
input.nextInt(); accepts an integer. Change it into input.nextDouble()
Scanner#nextInt()- Scans the next token of the input as an int.
and throws
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
input.nextInt() takes an input of type int
use
input.nextDouble()
Exception occur because of invalid input. you can add try catch block. See the below code.
For More information see this
public static void main(String[] args) {
try
{
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}