首页 > 解决方案 > 检查用户是否输入特定数据

问题描述

我想检查用户是否输入了特定的单词/字母,以便我可以根据他/她输入的内容运行一些代码。

这是我的代码:

import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;

public class EligibilityTest {

    public static void main(String[] args) {

        Scanner temperature = new Scanner(System.in);
        System.out.println("Press the 'T' key to check your temperature. ");

        double tempMeasure = ThreadLocalRandom.current().nextDouble(96, 98.9);

        // Here I would like to add an if statement to check if the user has input the 'T', and if yes, print the tempMeasure

    }
}


如何构造此 if 语句,以及如何将变量“tempMeasure”的十进制值保持为两位数?我发现 Java 输入非常复杂,因为我是在 Python 之后开始学习的,这相对容易得多。

标签: java

解决方案


需要添加

scan.nextLine()

检索用户的输入。然后你可以写 if 语句:

  public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Press the 'T' key to check your temperature. ");

        double tempMeasure = ThreadLocalRandom.current().nextDouble(96, 98.9);

        String temperature = scan.nextLine();
        
        if(temperature.equals("T")){
            System.out.println(tempMeasure);
        }
    }

推荐阅读