2015-01-03 68 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); 
    } 
} 
} 
相关问题