Java exercises and solutions: do while loop

do while loop



Exercise 1: By using do while loop, 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);


 }

}




Comments

Name:
Comment:
Enter the text:
CAPTCHA image

....................................................................................................................Home | Forum | About | Contact
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.
Copyright @ 2011-2013 worldbestlearningcenter. All Rights Reserved.
Home Programming Web DB & App Questions Exercises Tips Programs FAQs Download About
Computer-Wbest
Popular Pages
You might like