Exercise 1: Write Java program to prompt the user to choose the correct answer from a list of answer choices of a question.
The user can choose to continue answering the question or stop answering it. See the example below:
What is the command keyword to exit a loop in Java?
a. int
b. continue
c. break
d. exit
Enter your choice: b
Incorrect!
Again? press y to continue:
Solution:
import java.io.*;
public class JavaExercises
{
public static void main(String[] args)
{
selectChoice();
}
static void selectChoice(){
String choice;
String con="y";
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the command keyword to exit a loop in Java?");
System.out.println("a.quit");
System.out.println("b.continue");
System.out.println("c.break");
System.out.println("d.exit");
while (con.compareTo("y")==0)
{
System.out.print("Enter your choice:");
choice =br.readLine();
if (choice.compareTo("c")==0)
{
System.out.println("Congratulation!");
}
else if (choice.compareTo("q")==0 || choice.compareTo("e")==0) { System.out.println("Exiting...!"); break; }
else System.out.println("Incorrect!");
System.out.print("Again? press y to continue:");
con =br.readLine();
}
}catch(IOException e){}
}
}
Exercise 2:Write Java program to print the table of characters that are equivalent to the Ascii codes from 1 to 122.
The program will print the 10 characters per line.
Solution:
public class JavaExercises
{
public static void main(String[] args)
{
selectCharacters();
}
static void printCharacters(){
int i =1;
while (i <=122)
{
System.out.print((char)i+"\t");
if (i % 10 == 0)
System.out.print("");
i++;
}
No comments
Post a Comment