Hello, I\'m trying to do the numbers analysis program. When I run the code it gi
ID: 3622924 • Letter: H
Question
Hello,I'm trying to do the numbers analysis program. When I run the code it gives me an error that int i = 0; is all ready in use. How do i declare the value in the first part of the code and keep it in the rest to make it work?
I'm not very good at this so please explain it in simple terms.
Thank You,
Rob
import java.util.Scanner; // Needed for Scanner class
import java.io.*; // Needed for File class
/**
* @(#)NumbersText.java
*
*
* @author
* @version 1.00 2011/1/21
*/
public class NumbersText {
/**
* Creates a new instance of <code>NumbersText</code>.
*/
public NumbersText() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the file name.
System.out.print("Enter the name of a file: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
final int SIZE = 12; // Assuming we know the size.
int[] numbers = new int[SIZE];
int i = 0;
while (inputFile.hasNext() && i < numbers.length)
{
numbers[i] = inputFile.nextInt();
i++;
}
inputFile.close();
//int [] numbers = new int[12];
int highest = numbers[0];
for (int i; i < numbers.length; i++)
{
if (numbers[i] > highest)
highest = numbers[i];
}
System.out.print("Highest: " + numbers[i]);
int lowest = numbers[0];
for (int i; i < numbers.length; i++)
{
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.print("Lowest: " + numbers[i]);
int total = 0; // Initialize accumulator
for (int i; i < numbers.length; i++){
total += numbers[i];
}
System.out.print("Total: " + numbers[i]);
//double total = 0; // Initialize accumulator
double average; // Will hold the average
for (int i; i < numbers.length; i++){
total += numbers[i];
average = total / numbers.length;
}
System.out.print("Average: " + average);
}
}
Explanation / Answer
The problem occurs when you are re-using the i variable in your for loops. You have already declared int i=0 and then you use it in your while loop. If you want to use the same variable, then just don't put anything inside the first expression of the for loop: e.g. for(; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.