Monday, January 25, 2016

Java Core Exercise 6: switch case Programming in Java

Exercise 1: Write a Java program to detect key presses. If the user pressed number keys( from 0 to 9), the program will tell the numbe... thumbnail 1 summary


Exercise 1: Write a Java program to detect key presses.

If the user pressed number keys( from 0 to 9), the program will tell the number that is pressed,  otherwise, program will show "Not allowed".
Solution:

import java.io.*;
public class JavaExercises
{
public static void main(String[] args)
{
   detectKey();
}
static void detectKey(){
char key=' ';
System.out.print("Press a number key:");
try{
key = (char)System.in.read();
}catch(IOException e){};
switch (key)
{
case '0': System.out.println("You pressed 0."); break;
case '1': System.out.println("You pressed 1."); break;
case '2': System.out.println("You pressed 2."); break;
case '3': System.out.println("You pressed 3."); break;
case '4': System.out.println("You pressed 4."); break;
case '5': System.out.println("You pressed 5."); break;
case '6': System.out.println("You pressed 6."); break;
case '7': System.out.println("You pressed 7."); break;
case '8': System.out.println("You pressed 8."); break;
case '9': System.out.println("You pressed 9."); break;
default: System.out.println("Not allowed!"); break;
      }
  }
}

Exercise 2: Write a Java program that allows the user to choose the correct answer of a question.
See the example below:
What is the correct way to declare a variable to store an integer value in Java?
a. int 1x=10;
b. int x=10;
c. float x=10.0f;
d. string x="10";
Enter your choice: c
Solution:
import java.io.*;
public class JavaExercises
{
public static void main(String[] args)
{
   selectChoice();
}
static void selectChoice(){
char ans=' ';
System.out.println("What is the correct way to declare a variable to store an integer value in Java?");
System.out.println("a. int 1x=10");
System.out.println("b. int x=10");
System.out.println("c. float x=10.0f");
System.out.println("d. string x=\"10\"");
System.out.print("Enter your choice:");
try{
ans = (char)System.in.read();
}catch(IOException e){};
switch (ans)
{
case 'a': System.out.println("Invalid choice!"); break;
case 'b': System.out.println("Congratulation!"); break;
case 'c': System.out.println("Invalid choice!"); break;
case 'd': System.out.println("Invalid choice!"); break;
default: System.out.println("Bad choice!");break;
}
}
}

No comments

Post a Comment