-1

I would like to check if the user has input a specific word/alphabet so that I can run some code on the basis of what s/he inputs.

This is my code:

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

    }
}


How do I construct this if statement, and how do I keep the decimal value for variable 'tempMeasure' in two digits? I find Java inputs pretty complex, since I started learning after Python, which is relatively much easier.

  • How would you do that in python? Once you read a line you can do any operation you want on the resulting string. – Federico klez Culloca Mar 26 '21 at 15:19
  • In Python, I would construct an if and else statement and check for the input (using an == operator), but in Java it prevents me from using the == operator in the if statement saying that it can't be applied to 'java.util.Scanner', 'char' @FedericoklezCulloca – Chaitanya S Mar 26 '21 at 15:23
  • 1
    Does this answer your question? [How can I read input from the console using the Scanner class in Java?](https://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java) – onkar ruikar Mar 26 '21 at 15:25
  • 1
    The scanner isn't the input, it's the thing that reads the input. Also, `==` in Java compares literal values or object references; use `.equals()` to compare object values (like strings), and it's even [more complicated](https://stackoverflow.com/questions/8081827/how-to-compare-two-double-values-in-java) to compare floating point values. – azurefrog Mar 26 '21 at 15:25

1 Answers1

1

Yoy need to add

scan.nextLine()

to retrieve input from user. And then you can write if statement:

  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);
        }
    }
Kwinto0123
  • 71
  • 5