2013-10-12 94 views
0

進一步下來,它一直說當兩個局部變量不能初始化時。不能似乎找到了問題錯誤:局部變量罐可能沒有被初始化

import java.io.*; 
import java.util.Scanner; //Scanner method 

public class Popcorn1 { 

    public static void main(String args[]) throws FileNotFoundException{ 

    printHeader(); 

    File file; 

    do { 
     Scanner in = new Scanner (System.in); 
     System.out.println("Enter the the file name"); 
     String filename = in.next(); 

     file = new File(filename); 
    } while(!file.exists()); 

    FileReader inputFile = new FileReader (file); 
    Scanner inFile = new Scanner(inputFile); 

    System.out.println("  PopCorn Co-op"); 
    System.out.println("          Production in Hundreds"); 
    System.out.println("          of Pint Jars Per Acre"); 
    System.out.println("         1 2 3 4 5 6"); 
    System.out.println("Farm Name      ---|---|---|---|---|---|"); 
    System.out.println(); 

    // Printing out title and table header for reader to easily read data 
    String errorMSG = " "; 

    while (inFile.hasNextLine()) { 
     String inputLine = inFile.nextLine(); 
     //System.out.print(inputLine); 
     int position; 
     String name; 
     int jars; 
     double acres; 

     position = inputLine.indexOf(',');       //Get the Location of the comma to use as a delimiter 

     name = inputLine.substring(0,position);     //Everything to the left of the comma is the farm name 

     System.out.printf("%-31s", name); 

     inputLine = inputLine.substring(position + 2,inputLine.length());   //rest of the string 
     Scanner line = new Scanner(inputLine); 

     if(line.hasNextDouble()) 
      acres = line.nextDouble(); 
     else 
      errorMSG += "There is missing data"; 

     if(line.hasNextInt()) 
      jars = line.nextInt(); 
     else 
      errorMSG += "There is missing data"; 

     int starsConversion =(int)(jars/acres/25);  **<-------- problem is here** 

     for (int i = 1; i < starsConversion; i++) { 
      if(i == 20) 
       System.out.print("#"); 
      else 
       System.out.print("*"); 
     } 
     if (starsConversion < 20) { 
      for (int i = 1; i < (21 - starsConversion); i++) { 
       System.out.print(" "); 
      } 
      System.out.print("|");} 
      System.out.println(); //go to the next line 

     } 

     System.out.println(errorMSG); 

    } 
} 

回答

0

有一種情況jars從未初始化,具體地說,如果line.hasNextInt()false的執行路徑。

要使用它,您必須確保jars始終被初始化爲某種東西。您可以在if之前將其初始化爲0

0

如果if(line.hasNextInt())在第一次運行時爲false,會發生什麼情況?