Cadecious Cadecious - 1 year ago 52
Java Question

Can somebody tell me why fVI is returning 0 every time when I am setting it to the first valid input the Scanner reads

In the method getHighestValue, why is fVI returning 0 every time? How do I get it to set it to the first valid input? I want to end up comparing it to each input that is entered to find the highest value.

public static void main(String[] args) {
int numCount;
int numScores = 0;
int values;
int fVS; //fVS = First Valid Score

Scanner input = new Scanner(;
System.out.println("Enter test scores between 50 and 109");

numScores = getCount(input);
fVS = getHighestValue(input);
if (numScores == 0) {
System.out.println("No scores read");
} else {
System.out.println(numScores + " " + fVS);
}// ends main

//Counts the number of inputs
public static int getCount(Scanner input) {
int values;
int numberOfScores = 0;

while (input.hasNextInt()) {
values = input.nextInt();

if (values > 49 && values < 110) {
} // ends while loop that scans for next int and counts each score input
return numberOfScores;
}// ends getCount

//Finds the highest value
public static int getHighestValue(Scanner input) {
int fVI = 0;
int value;
int numberOfScores = 0;

while (input.hasNextInt()) {
value = input.nextInt();

if (value > 49 && value < 110) {
fVI = value;


return fVI;
}// ends getHighestValue

Answer Source

You have one scanner which getCount() will read integers from until there are no more left. Then getHighestValue() will also read integers from that scanner until there are none left.

But, and here's the rub, getCount() has already exhausted the scanner so there can be none left for getHighestValue().

Your best bet is to probably read them into a collection of some description so they're available to both functions.

So have a new function that reads the scanner once and populates and returns (for example) a Vector, then pass that vector to the two functions for processing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download