cresjoy cresjoy - 4 months ago 12
Java Question

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.

Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.

I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.

By the way Heres a simple input output

Input

10
0
-1
Q


Output

Average = 3.0
Max = 10.0


My code

public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{

String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}

}


I'm getting an error at
double x = inputTwo.nextDouble();
.

Heres my thought process.

Lets make a flag and keep looping asking the user for a number until we hit
Q
. Now my issue is that of course the number needs to be a double and the
Q
will be a string. So my attempt was to make two scanners

Heres how my understanding of scanner based on chapter two in my book.

Alright so
import Scanner
from
java.util library
so we can use this package. After that we have to create the
scanner
object. Say
Scanner input = new Scanner(System.in);
. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely
input
here). The reason this is nice is that it allows us to set our Scanner to
doubles
and
ints
etc, when it comes as a default
string
( via
.nextDouble(), .nextInt()
);

So since I set result to a
string,
I was under the impression that I couldn't use the same
Scanner
object to get a
double
, so I made another
Scanner
Object named
inputTwo
, so that if the user doesn't put
Q
(i.e puts numbers) it will get those values.

How should I approach this? I feel like i'm not thinking of something very trivial and easy.

Answer

You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!