2016-11-21 161 views
-1

嘿,我正在一個項目工作,輸出什麼也沒給。我已經嘗試了一大堆除了將System.out.print移動到只打印出無數個隨機數字的大括號之外的所有輸出都沒有輸出的東西。它是一個短代碼,所以在這裏它是:Java程序運行,但沒有輸出

import java.util.Scanner; 
import java.io.IOException; 
import java.io.File; 

public class ACSLPrintsJR { 
public static int value(int num){ 
int [] array = {0,16,16,8,8,4,4,2,2,1,1}; 
    return array[num]; 
} 

public static void main(String[] args) throws IOException { 
    int top = 1; 
    int bottom = 1; 
    File file = new File("ACSLPRINTSJR.IN"); 
    Scanner scan = new Scanner(file); 
    int num = scan.nextInt(); 
    while (num != 0){ 
    num = scan.nextInt(); 
     if (num % 2 == 0) 
      top += 1 + value(num); 
     else 
      bottom += 1 + value(num); 
    }  
    System.out.println(top+"/"+bottom); 
scan.close(); 
} 

} 

正如我說沒有輸出和這裏是IN的內容文件

輸入是:

預期輸出是:

19/3

1/1

電流輸出: 沒有

+3

您需要使用'num = scan.nextInt()'在while循環中更新'num'。 –

+1

瀏覽紙上的代碼,看看它在循環中做了什麼。如果你這樣做了,你會發現它從來沒有從掃描儀獲取數據。 –

+0

我這樣做了,現在它實際上輸出了一些東西,但它不是正確的輸出,它只能用於一行 – icecreeper01

回答

1

您需要從循環中的掃描儀讀取數據。以下是爲您更新的代碼。

public class ACSLPrintsJR { 
    public static int value(int num) { 
     int[] array = {0, 16, 16, 8, 8, 4, 4, 2, 2, 1, 1}; 
     return array[num]; 
    } 

    public static void main(String[] args) throws IOException { 
     File file = new File("ACSLPRINTSJR.IN"); 
     Scanner scan = new Scanner(file); 
     int num; 
     while (scan.hasNext()) { 
      int top = 1; 
      int bottom = 1; 
      while ((num = scan.nextInt()) != 0) { 
       if (num % 2 == 0) 
        top += value(num); 
       else 
        bottom += value(num); 
      } 
      System.out.println(top + "/" + bottom); 
     } 
     scan.close(); 
    } 
} 
+0

我試過了,但它返回了錯誤的輸出 – icecreeper01

+0

您的預期輸出是什麼? –

+0

虐待添加到描述 – icecreeper01

1

您已經在這裏創造一個無限循環:

int num = scan.nextInt(); 
while (num != 0){ 
    if (num % 2 == 0) 
     top += 1 + value(num); 
    else 
     bottom += 1 + value(num); 
}  
System.out.println(top+"/"+bottom); 

您在num讀取你的檔案,如果num不是零,廁所p無限地運行,因爲你永遠不會修改while循環中的num的值。我冒昧地猜測,你需要說:

int num = scan.nextInt(); 
do{ 
    if (num % 2 == 0) 
     top += 1 + value(num); 
    else 
     bottom += 1 + value(num); 

    num = scan.nextInt(); 
}while(num != 0); 
System.out.println(top+"/"+bottom); 

不過,我不知道你的代碼的確切意圖,所以這可能不是所期望的方法。不過,您需要在while循環中修改num,否則您將無限循環。

+0

確實意味着它在它的大括號內執行的事情,而num!= 0? – icecreeper01

+0

我改變了它,但它仍然返回5/4 – icecreeper01

+0

@ icecreeper01,'do-while'循環是一個循環,其中第一次迭代在條件(在這種情況下爲'num!= 0)被檢查之前執行。 – SpencerD

0

num變量永遠不會改變它的值,我認爲你必須爲你的文件中的每一行這樣做。你必須更新你的後衛,比如while(scan.hasNextInt()),這樣你就可以繼續前進,直到文件中有一個int值,然後用scan.nextInt()來選擇它。其餘代碼基本相同。我現在看到了你的編輯,現在如果你用`scan.nextInt()'選擇的值等於0,你必須打印你需要的值,重置你的計數器變量,並繼續進入循環,直到你選擇最後0在您的文件中。我希望我足夠清楚。