2015-01-03 70 views
0

我正在休息並試圖讓我的Java技能備份,因此我正在研究一些隨我在codeeval上找到的隨機項目。我在打開一個使用fizzbuzz程序的java文件時遇到了麻煩。我有真正的fizzbuzz邏輯部分,工作得很好,但打開文件證明是有問題的。從文件中讀取空格分隔的數字

因此可以推測,文件將作爲主要方法的參數打開;所述文件將包含至少1行;每行包含3個由空格分隔的數字。

public static void main(String[] args) throws IOException { 
    int a, b, c;   
    String file_path = args[0]; 

    // how to open and read the file into a,b,c here? 

    buzzTheFizz(a, b, c); 

} 
+0

是的,但問題出在哪裏? 「開放是有問題的」 - 一個文件不是潘多拉盒子 - 所以你是什麼意思? – laune

+0

我希望你知道,當你傳遞給'buzzTheFizz'時,變量'a','b'和'c'將始終爲'0'。 – Tom

+0

@Tom你跳到前面:-) – laune

回答

1

您可以像這樣使用Scanner;

Scanner sc = new Scanner(new File(args[0])); 
a = sc.nextInt(); 
b = sc.nextInt(); 
c = sc.nextInt(); 

默認情況下,掃描程序使用空格和換行符作爲分隔符,正是你想要的。

+0

可能需要一個循環 - 文件中會有那麼多行Fizz中有氣泡。 – laune

+0

不知道嘶嘶響是什麼。我只是回答如何閱讀3個數字。 – eckes

+0

Fizz是一種混合飲料,總是添加碳酸水。泡沫是從底部向上升起的圓形物體。 - 在問:「至少有一條線」。 – laune

1
try { 
    Scanner scanner = new Scanner(new File(file_path)); 
    while(scanner.hasNextInt()){ 
     int a = scanner.nextInt(); 
     int b = scanner.nextInt(); 
     int c = scanner.nextInt(); 
     buzzTheFizz(a, b, c); 
    } 
} catch(IOException ioe){ 
    // error message 
} 
1

使用循環讀取整個文件,有樂趣:

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

public class Main { 

public static void main(String[] args) { 
    int a = 0; 
    int b = 0; 
    int c = 0; 
    String file_path = args[0]; 

    Scanner sc = null; 
    try { 
     sc = new Scanner(new File(file_path)); 

     while (sc.hasNext()) { 
      a = sc.nextInt(); 
      b = sc.nextInt(); 
      c = sc.nextInt(); 
      System.out.println("a: " + a + ", b: " + b + ", c: " + c); 
     } 
    } catch (FileNotFoundException e) { 
     System.err.println(e); 
    } 
} 
} 
相關問題