Can we use a user input to define what's it's category in an array ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can we use a user input to define what's it's category in an array ?

All I want is the user to type in a number ( a temperature in Celcius) like the code under, and the output would be a word from the array sorted out by few "if else". I'm begining and just trying to learn. import java.util.Scanner; class Program { public static void main(String[] args) { String[ ] myTemps = {"Cold", "Mild", "Warm", "Hot"}; int x = 0; Scanner thermometer = new Scanner(System.in); System.out.println("What is the temperature in celcius?"); int temperature = thermometer.nextLine(); //x = temperature; if(temperature > 0) { if(temperature > 15) { if(temperature > 30) { System.out.println(myTemps[3]);} else { System.out.println(myTemps[2]);} }else{ System.out.println(myTemps[1]);} }else{ System.out.println(myTemps[0]); } } }

28th Sep 2020, 3:21 AM
Maxime Dubé
Maxime Dubé - avatar
6 Answers
+ 2
int temperature = Integer.parseInt(thermometer.nextLine()); Or you can just use int temperature = thermometer.nextInt(); assuming you want to parse the int
28th Sep 2020, 3:31 AM
Odyel
Odyel - avatar
+ 1
O, ye, when you use .nextLine() it reads it as a string, so to assign it to an int value you'd have to convert it with Integer.parseInt(string); or you can read it as an int with (scannerObj).nextInt();
28th Sep 2020, 3:50 AM
Odyel
Odyel - avatar
0
Odyel, Not sure what it would do with the parse... but I tried both and it still does the same error. Here if you want to see the code link: https://code.sololearn.com/c5u09tnXQCit/?ref=app https://code.sololearn.com/c5u09tnXQCit/?ref=app
28th Sep 2020, 3:43 AM
Maxime Dubé
Maxime Dubé - avatar
0
Works fine for me, what are you inputing? I just entered "75"
28th Sep 2020, 3:45 AM
Odyel
Odyel - avatar
0
Oh.. wait, sorry, my fault, it works perfectly, thanks! Glad to know that only 1 line was wrong
28th Sep 2020, 3:47 AM
Maxime Dubé
Maxime Dubé - avatar
0
Thanks, it's clear now!
28th Sep 2020, 3:51 AM
Maxime Dubé
Maxime Dubé - avatar