Click here to Skip to main content
14,454,989 members
Rate this:
Please Sign up or sign in to vote.
In this case, I have identified my numbers to produce the right results in the console. I have created about three if statements, but whatever number I put in the console using the scanner, it always outputs the first condition and ignores the rest.

What I have tried:

import java.util.Scanner;
public class Temperature{
    public static void main(String[]args){
        Scanner keyboard = new Scanner(System.in);
        int option = keyboard.nextInt();
        if (option>-20)
        {
                System.out.print("Too Cold");
        }
        else if (option<=-20&&option>=-11){
                System.out.print("Very Cold");
        }
    }
}
Posted
Updated 14-Feb-20 7:06am
v2
Comments
Gerry Schmitz 13-Feb-20 20:49pm
   
-11 is greater that -20, the first option.

And a number that is less than -20 and greater then -11, at the same time, does not exist. Draw yourself picture.
Gerry Schmitz 13-Feb-20 20:49pm
   
-11 is greater that -20, the first option.

And a number that is less than -20 and greater then -11, at the same time, does not exist. Draw yourself picture.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Advice: it don't hurt to put spaces in code.
Your condition is wrong:
else if (option <= -20 && option >= -11){
        System.out.print("Very Cold");
}

It is 'Very Cold' if option is lower or equal to -20 (like -20 -25 -30 -35 ...) and at same time option is greater or equal to -11 (like -11 -10 -8 -5 -2 -1 0 10 20 ...)

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100