我也主要使用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();
}
}
我相当肯定会得到一个你可以说的int
Integer.parseInt(keyboardInput.readLine());
但如果我想要一个字符串
我该怎么办?答案 0 :(得分:5)
keyboardInput.readLine()
已经返回一个字符串,所以你应该只做:
return keyboardInput.readLine();
(更新)
readLine
方法抛出IOException
。你要么抛出异常:
public String getFlavour() throws IOException {
...
}
或者你在方法中处理它。
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;
}