Reputation: 27
I'm on my winter break and trying to get my Java skills back up to snuff so I am working on some random projects I've found on codeeval. I'm having trouble opening a file in java doing the fizzbuzz program. I have the actual fizzbuzz logic part down and working just fine, but opening the file is proving problematic.
So presumably, a file is going to be opened as an argument to the main method; said file will contain at least 1 line; each line contains 3 numbers separated by a space.
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);
}
Upvotes: 0
Views: 101
Reputation: 2542
Using a loop it reads the whole file, have fun:
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);
}
}
}
Upvotes: 1
Reputation: 31290
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
}
Upvotes: 1