Ask Question
11 May, 19:35

Re-type the code and fix any errors. The code should convert non-positive numbers to 1. if (userNum > 0) System. out. println ("Positive."); else System. out. println ("Non-positive, converting to 1."); userNum = 1; System. out. println ("Final: " + userNum); Common student error: Changing the order of the lines. You only need to fix the existing code. import java. util. Scanner; public class ConvertNegative { public static void main (String [] args) { Scanner scnr = new Scanner (System. in); int userNum; userNum = scnr. nextInt (); / * Your solution goes here * / }}

+2
Answers (1)
  1. 11 May, 20:59
    0
    The above question code has only one wrong statement with the curly braces. If the user added the curly braces to the else part including two statements, then the code will display the correct result. The code after added the curly braces is as follows:-

    if (userNum > 0) / /Taken from the question.

    System. out. println ("Positive."); / /Taken from the question.

    else / /Taken from the question.

    { / / it will be added to the question code.

    System. out. println ("Non-positive, converting to 1."); / /Taken from the question.

    userNum = 1; / /Taken from the question.

    } / / it will be added to the question code.

    System. out. println ("Final: " + userNum); / /Taken from the question.

    Output:

    If the user inputs 4 then it will print the "positive number". If the user inputs - 9 then it will print the 1 as the final value

    Explanation:

    The question code is not given the right result for the value of a positive number. The question said that if the value is negative then only the 1 will be printed. But the question code will print 1 for the case of positive value also. It is because there are no curly braces in the else-statement. So the else statement took only one statement within its block which is a print statement. And the other statement is outside the else block which is assigned the 1 value to the final variable which will be printed. So if the curly braces are fixed to decide the two statement, the print statement, and the assignment statement, then it will not print 1 for a positive value.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Re-type the code and fix any errors. The code should convert non-positive numbers to 1. if (userNum > 0) System. out. println ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers