[英]Java Input File wont print
我正在編寫一個作業,我需要從java中輸入的文件中打印3個不同的樂譜組的平均值。 平均值必須四舍五入到小數點后兩位。 我嘗試創建掃描程序,以便輸入文件中的小數可以添加並平均,但是當我點擊運行時,netbeans只會運行而沒有打印出來。 我也沒有收到錯誤。 關於如何讓它運行的任何提示將不勝感激。
輸入文件內容:7.88 6.44 5.66 3.44 7.50 9.80 4.33 2.31 8.99 7.62 3.67 4.39
``這是代碼(已導入所有必需的導入)
public static void main(String[] args) throws IOException {
{
Scanner sc = new Scanner(new File("Gym.in"));
double Number = sc.nextFloat();
{
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
Scanner sf = new Scanner(new File("Gym.in"));
int maxIndx = -1;
String text[] = new String[100];
while (sf.hasNext())
;
{
maxIndx++;
text[maxIndx] = sf.nextLine();
System.out.println(text[maxIndx]);
}
sf.close();
String answer;
double sum;
double average;
for (int j = 0; j <= maxIndx; j++) {
StringTokenizer st = new StringTokenizer(text[j]);
Scanner sg = new Scanner(text[j]);
System.out.println(text[j]);
Scanner ss = new Scanner(text[j]);
sum = 0;
average = sum / 10;
answer = "For Competitor #1, the average is: ";
while (sc.hasNext()) {
double i = sc.nextDouble();
answer = answer + i;
sum = sum + i;
}
answer = answer + average;
System.out.println(answer);
}
}
}
}
這段代碼有幾個問題 - 一個是你期望的'.'
作為小數點字符,但在我的語言環境中它是','
,所以我得到的第一件事是java.util.InputMismatchException
。
無論如何,你的代碼似乎沒有做任何事情的原因是這些方面:
while (sf.hasNext())
;
這實際上是一個無限循環。 當您的掃描儀有更多令牌要傳遞時,您正在循環,但您永遠不會檢索下一個令牌。 因此hasNext()
將永遠返回true
。
如果你刪除;
然后你的代碼就會運行。 我沒有驗證結果。
您還需要重新計算平均值:使用代碼,您的平均值將始終保持為0.0
:
sum = 0;
average = sum / 10;
...
answer = answer + average;
System.out.println(answer);
我也不確定你為什么要將總和除以10 - 在你的情況下這應該是12(假設“每組得分”在輸入文件中是一行)。 總而言之,您的方法並不是太糟糕 - 您基本上必須刪除一些不必要的代碼並以正確的順序放置第二個循環中的語句:)
for (int j = 0; j <= maxIndx; j++) {
double sum = 0;
double average = 0;
Scanner ss = new Scanner(text[j]);
String answer = "For Competitor #1, the average is: ";
while (sc.hasNext()) {
double i = sc.nextDouble();
sum = sum + i;
}
average = sum / 12; // better use number of tokens read instead of hard coded 12
answer = answer + average;
System.out.println(answer);
}
最后,您不需要將每行讀入String
數組 - 只需讀取一行並立即處理它。 當文件中有超過100行時,這可以節省內存並避免IndexOutOfBoundsException
。 我把這個作為一個練習:)
去除 ; 過了一會兒(sf.hasNext())
更改
while (sf.hasNext())
;
{
成
while (sf.hasNext())
{
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.