如何从缓冲的阅读器输入字符串?(How do i input a string from a buffered reader?)
我也主要使用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());但如果我想要一个字符串怎么办?
Im used too using Scanner mainly and want too try using a buffered reader: heres what i have so far
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
Integer.parseInt(keyboardInput.readLine());but what do i do if i want a String
最满意答案
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; }keyboardInput.readLine() already returns a string so you should simply do:
return keyboardInput.readLine();(update)
The readLine method throws an IOException. You either throw the exception:
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; }更多推荐
发布评论