以下是我要解决的问题https://www.codeeval.com/open_challenges/100/
这是我的解决方案:
public static void main(String[] args) {
// TODO code application
File file = null;
try{
FileReader f = new FileReader("C:\\Users\\ranaa\\Desktop\\merna1.txt");
BufferedReader br = new BufferedReader(f);
String getContent;
while((getContent=br.readLine())!=null){
int content = Integer.parseInt(getContent);
System.out.println(content);
if(content %2==0)
System.out.println("1");
else
System.out.println("0");
}
}catch(Exception e){
System.out.println(e);
}
}
没有输出对我来说也不例外。
有人能帮助我吗?
答案 0 :(得分:1)
在看到我的代码之前
首先,在try catch block with resources
中放置任何可关闭的内容是很好的,因此无需担心在结束时关闭它,因为关闭连接是隐式完成的。读这个:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
其次,如何使用BuffeRreader
只是看看这个
How to use Buffered Reader in Java
第三,如何使用Scanner
只看一下这个
How can I read input from the console using the Scanner class in Java?
代码:
String filePath = "C:\\Users\\KICK\\Desktop\\number.txt";
File file = new File(filePath);
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
int current = Integer.parseInt(line);
if( current % 2 == 0)
System.out.println("1");
else
System.out.println("0");
}
} catch (Exceptio e) {
System.out.println(e);
}
或者您可以使用Scanner
类
代码:
String filePath = "C:\\Users\\KICK\\Desktop\\number.txt";
File file = new File(filePath);
try(Scanner input = new Scanner(file)){
while(input.hasNext()){
int current = Integer.parseInt(input.next());
if( current % 2 == 0)
System.out.println("1");
else
System.out.println("0");
}
}catch(Exception e){
System.out.println(e);
}
输出:
0
0
1
number.txt内容:
701
4123
2936