Monday, January 25, 2016

Java Core Exercise 9: do while loop programming in java language

Exercise 1: By using do while oop, write Java program to prompt the user to choose the correct answer from a list of answer choices of a ... thumbnail 1 summary

Exercise 1: By using do while oop, 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;
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");
do
{
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();
} while (con.compareTo("y")==0);
}catch(IOException e){}

  }
}

Exercise 2: By using  do while loop, 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)
{
 printCharacters();
}
static void printCharacters(){
int i =1;
do
{
  System.out.print((char)i+"\t");
  if (i % 10 == 0)
    System.out.println("");
  i++;
    }while(i<=122);
 }
}

No comments

Post a Comment