1

我也主要使用扫描仪,也想尝试使用缓冲阅读器:这是我到目前为止所拥有的

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());

但是如果我想要一个字符串我该怎么办

4

1 回答 1

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;
}
于 2009-12-02T14:10:50.747 回答