Ask Question

What is wrong with the following switch statement? int ans; System. out. print ("Type y for yes or n for no"); ans = scan. nextInt (); switch (ans) { case 'y': case 'Y': System. out. println ("You said yes"); break; case 'n': case 'N': System. out. println ("You said no"); break; default: System. out. println ("invalid answer"); }

+1
Answers (1)
  1. 10 March, 23:34
    0
    In this question the ans variable data-type is int, that is wrong.

    Explanation:

    In the above code the ans variable int that is used for taking integer value. and In the switch statement, we pass the value that is character so the program will give the error. To solve this error we will declare the ans variable as char and taking input from the scanner class like this (ans = scan. next (). charAt (0); ) where ans is variable, scan is the object of scanner class and next (). charAt (0) is used to take input. that is store in ans variable.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “What is wrong with the following switch statement? int ans; System. out. print ("Type y for yes or n for no"); ans = scan. nextInt (); ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers