3. How to Read Input from the Console or Keyboard in Java

preview_player
Показать описание
---
My Gear (づ⌐■ ͜ʖ■)づ
Follow me ┴┬┴┤( ͡° ͜ʖ├┬┴┬
---
Reading input from the console enables the program to accept input from the user.

Obviously, this is not convenient, so instead you can
use the Scanner class for console input.

as follows:

makes a Scanner object and assigns its reference to the variable input. An object may invoke its methods. To invoke a method on
an object is to ask the object to perform a task. You can invoke the nextDouble() method to read a double value as follows:

How should I do it now?
You can use Scanner class
Import first :
Then you use like this.
Side note : If you are using nextInt() with nextLine() you probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine() then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping
Рекомендации по теме
Комментарии
Автор

Question 2
Write a program that reads a character from the user and then uses a switch statement to achieve what the following if statement does.

if ((choice == ‘A’) || (choice == ‘a’))
printf(“Action movie fan\n”);
else if ((choice == ‘C’) || (choice == ‘c’))
printf(“Comedy movie fan\n”);
else if ((choice == ‘D’) || (choice == ‘d’))
printf(“Drama movie fan\n”);
else
printf(“Invalid choice\n”);


Name the source code of this program as P2.java and name the compiled class code as P2.class inside the sub-directory lab1.

Test cases: ‘a’, ‘A’, ‘c’, ‘C’, ‘d’, ‘D’, ‘b’, ‘B’.

Expected outputs: ‘a’, ‘A’ – Action movie fan; ‘c’, ‘C’ – Comedy movie fan; ‘d’, ‘D’ – Drame movie fan; ‘b’, ‘B’ – Invalid choice.




himelsarkar
visit shbcf.ru