小编kie*_*ell的帖子

使用子字符串从Java中的字符串中获取整数和字符?

要求用户输入温度,然后用户输入数字,后跟摄氏温度或华氏温度的C或F。然后程序将识别温度以及测量温度的单位-使用此数据可以告诉您“水”是固态,液态还是气态。

我尝试了以下

public static void main(String[] args) {
    Scanner myScan = new Scanner(System.in);

    System.out.print("Enter THE temp: ");
    String ent = myScan.next();


    int temp = Integer.parseInt(ent.substring(0,4));

    //char type = ent.charAt();
    //System.out.println(temp);
    // System.out.println(type);

    if (temp >= 100) {
        System.out.println("The water is gaseous");
    } else if (temp < 0) {
        System.out.println("The water is solid");
    } else {
        System.out.println("the water is liquid");
    }

}
Run Code Online (Sandbox Code Playgroud)

当我将(0,4)放入temp子字符串中时,我会认为输出将是输入的前3个数字。相反,当我输入1 int或3时,我得到一个错误“ java.lang.StringIndexOutOfBoundsException”。

java substring

3
推荐指数
1
解决办法
89
查看次数

标签 统计

java ×1

substring ×1