java 如何从缓冲阅读器输入字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1833108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i input a string from a buffered reader?
提问by OVERTONE
Im used too using Scanner mainly and want too try using a buffered reader: heres what i have so far
我也主要使用 Scanner 并且也想尝试使用缓冲阅读器:这是我目前所拥有的
import java.util.*;
import java.io.*;
public class IceCreamCone
{
// variables
String flavour;
int numScoops;
Scanner flavourIceCream = new Scanner(System.in);
// constructor
public IceCreamCone()
{
}
// methods
public String getFlavour() throws IOexception
{
try{
BufferedReader keyboardInput;
keyboardInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" please enter your flavour ice cream");
flavour = keyboardInput.readLine();
return keyboardInput.readLine();
}
catch (IOexception e)
{
e.printStackTrace();
}
}
im fairly sure to get an int you can say
我相当肯定会得到一个 int 你可以说
Integer.parseInt(keyboardInput.readLine());
but what do i do if i want a String
但是如果我想要一个字符串我该怎么办
回答by bruno conde
keyboardInput.readLine()already returns a string so you should simply do:
keyboardInput.readLine()已经返回一个字符串,所以你应该简单地做:
return keyboardInput.readLine();
(update)
(更新)
The readLinemethod throws an IOException. You either throw the exception:
该readLine方法抛出一个IOException. 你要么抛出异常:
public String getFlavour() throws IOException {
...
}
or you handle it in your method.
或者你用你的方法处理它。
public static String getFlavour() {
BufferedReader keyboardInput = null;
try {
keyboardInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" please enter your flavour ice cream");
// in this case, you don't need to declare this extra variable
// String flavour = keyboardInput.readLine();
// return flavour;
return keyboardInput.readLine();
} catch (IOException e) {
// handle this
e.printStackTrace();
}
return null;
}

