• Register
0 votes
326 views

Problem :

I am facing issues with following Java  code and unable to figure out the cause behind the issue, I guess it is some logical error but I am unable to figure it out, my all results are ending up as 0.

Please find below the Java Code:

import java.util.Scanner;
public class MyConvertNegative {
   public static void main (String [] args) {
      int myUserNum = 0;
      if (myUserNum >= 0)
         System.out.println("Poitive");
      else
         System.out.println("Negative; Converting To 0");
         myUserNum = 0;
         System.out.format("Final Result: %d", myUserNum);
         System.out.println(""); 
      return;
   }
}

Please let me know how can I fix this issue?

6 5 3
7,540 points

1 Answer

0 votes

Solution :

In your code I can see that you have the multi line conditions so you need to set the brackets. Without them your else block will just execute the first line of the code after it. So in your case the line executed is  System.out.println("Negative; Converting To 0");. So in that case your variable myUserNum would be set to 0 as the next line will not be the part of the else block anymore. So you need to follow the More than 1 line = brackets.

public class MyConvertNegative {
    public static void main (String [] args) {
        int myUserNum = 0;
        if (myUserNum >= 0)
            System.out.println("Poitive");
        else{
            System.out.println("Negative; Converting To 0");
            myUserNum = 0;
            System.out.format("Final Result: %d", myUserNum);
            System.out.println(""); 
        }
        //return; -> No need for the return as your main function is not returning any value.
    }
}
9 7 4
38,600 points

Related questions

2 votes
2 answers 170 views
170 views
Problem: Hello all, I am a noob to this java programming. I started learning it a few days back. Re-type the code and fix any errors. the code should convert non-positive numbers to 1. As long as I understand this problem is sying to convert a negative number to ... but that’s not enough for my case. If your understanding is up to this level, please pull me up from the grave LOL. Thanks.
asked Mar 19 Gavin 15.3k points
0 votes
1 answer 11 views
11 views
Please explain the following about "Cannot find symbol", "Cannot resolve symbol" or "Symbol not found" errors in JAVA?
asked Sep 28 Xaimax 9.5k points
0 votes
1 answer 6 views
1 vote
1 answer 50 views
50 views
Problem: I wrote a program in python that asks the user for a number n and prints the sum of the numbers 1 to n: x = 1, addition = 0 n = int(input('Please enter a number:')) for i in range(x, n): addition = addition + i print (addition) But when ... n): TypeError: 'tuple' object cannot be interpreted as an integer Is there any thing that is missing from my code. Please help me to solve this out.
asked Jun 10 samhaz 5k points
0 votes
1 answer 121 views