2017-04-11 33 views
1

所以我的計劃應該說,這是從我的輸入文件是什麼類型的令牌。我的第二種方法應該是將任何來自鍵盤的輸入寫入輸出文件,直到用戶輸入停止。問題是我的第一個方法不會將整數輸出到正確的類型。我的第二種方法將只停止在輸出文件。這是我的代碼。任何幫助將非常appriciated。文件輸入和輸出方法發出

public class R16 { 
public void readFile(String inputFile) { 

    try { 
     File in = new File(inputFile); 
     Scanner scan = new Scanner(in); 
     while (scan.hasNext()) { 
      if (scan.hasNextInt()) { 
       System.out.println("Integer: " + scan.nextInt()); 
      } 
      if (scan.hasNext()) { 
       System.out.println("String: " + scan.next()); 
      } 

      if (scan.hasNextDouble()) { 
       System.out.println("Double: " + scan.nextDouble()); 
      } 

     } 

     scan.close(); 

    } catch (IOException e) { 
     System.out.println("Error, not good"); 

    } 

} 

public void writeFile(String outputFile) { 
    try { 
     File out = new File(outputFile); 
     PrintWriter w = new PrintWriter(out); 
     Scanner scan= new Scanner(System.in); 
     System.out.print("Enter Text: "); 
     while(!scan.next().equals("stop")){ 
      w.print(scan.next()); 

     } 








     w.close(); 
     scan.close(); 

    } catch (IOException e) { 
     System.out.println("Error, it just got real"); 
    } 

} 

public static void main(String[] args) { 
    R16 test = new R16(); 
    test.readFile(args[0]); 
    test.writeFile(args[1]); 

} 

}

+1

也許你應該做的第二兩個'if'語句轉換成別的'陳述if',也許你應該檢查'hasNextDouble()'hasNext前'()'。其實,這將使'hasNext()'最後,和多餘的,因爲你已經檢查在'while'循環,所以一個簡單的'else'就足夠了。 – Andreas

+0

它的作品謝謝你。 –

回答

2

在你的循環,你檢查stop然後扔掉所有的輸入。

while(!scan.next().equals("stop")){ 

嘗試使用類似

String input; 
while (!(input = scan.next()).equals("stop")) { 
    w.print(input); 

現在在循環中,您可以訪問它包含了輸入字符串輸入變量。

+0

'next()'不返回「行」。 – Andreas

+0

梅,行,輸入。足夠近。 –

+0

修復它,謝謝 –