Reputation: 91
I've been writing a Java application that takes in 6 values (2 in the first section, 3 in the second, 1 in the last). Then it outputs the average the first data set, then the second, and then the total average.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your test grades.");
double t1 = scan.nextInt();
double t2 = scan.nextInt();
System.out.println("Please enter your quiz grades.");
double q1 = scan.nextInt();
double q2 = scan.nextInt();
double q3 = scan.nextInt();
System.out.println("Please enter your homework average.");
double hmw = scan.nextInt();
double arc1 = ((t1 + t2) / 2);
System.out.println("Test Average:" + arc1);
double arc2 = ((q1 + q2 + q3) / 3);
System.out.println("Quiz Average:" + arc2);
double arcfinal = ((arc1 * 0.5) + (arc2 * 0.3) + (hmw * 0.2));
System.out.println("Final Grade:" + arcfinal);
}
}
I cannot figure out what is wrong in my coding. Here is my error:
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 average.main(Main.java:13)
Upvotes: 0
Views: 286
Reputation: 46
I think I ran into a similar problem not too long ago. You will need to validate your input before you store it. To do that, it is important to visualize the scanner has a "pipe" with a string going through the entrance of the pipe (user input) and different possible values (just a text string, an int, a double, a binary, or other formats) "coming out" from the other end of the pipe (which is your code reads the scanner in your code.)
Here is the list of validations that it seems like you want to implement:
I have written below an example of what should happen each time you are looking for one of your grades:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class Main{
static double t1, t2, q1, q2, q3, hmw;
public static void main (String str[]) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your test grades.");
System.out.println("Enter grade one: ");
// While there is something in the pipe
while(scan.hasNext()!=false)
{
// Check if this value is an integer
if(scan.hasNextInt())
{
t1 = scan.nextInt();
System.out.println("Successful input. Grade entered: "+t1);
break;
}
// it is not an integer, display a message saying it is an invalid input
else
{
// Flush the invalid input
scan.next();
System.out.println("Invalid input detected.");
}
}
//... (rest of the code)
Remember that, in this example, if you enter [any amount of garbage non number text] + space + an integer, it will scroll through the entire thing and find the integer.
Upvotes: 1