我正在解决代码厨师的问题。我遇到了一个问题,所有的说法都是我的错误答案。我想测试我的程序以查看其输出,但它从文本文件读取输入,我无法弄清楚如何使用eclipse,我的代码如下:
import java.io.*;
class Holes {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(r.readLine());
for (int i =0; i<testCases; i++)
{
int holes = 0;
String s = r.readLine();
for (int j= 0; j< s.length(); j++)
{
char c = s.charAt(j);
if (c == 'B')
holes += 2;
else if (c== 'A' || c== 'D' ||c== 'O' ||c== 'P' ||c== 'Q' ||c== 'R' )
{
holes +=1;
}
System.out.println(holes);
}
}
}
}
答案 0 :(得分:1)
将文件夹添加到该文件夹中的eclipse项目中添加输入文件,然后使用BufferReader读取它,如下所示 BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
另一种方法是将路径作为参数传递给程序 如下图所示
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
当你运行应用程序运行配置时如何做到这一点,你会发现args你可以在其中添加任何路径,例如c:\ myinput.txt 希望这有帮助
答案 1 :(得分:1)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}