Ask Question
30 December, 02:06

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 * / }}

+4
Answers (1)
  1. 30 December, 05:05
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers