Reputation: 3
I want to write a simple loop for the program to go back and restart it again.
Just a simple 1 question program. Then the system ask if the user want to do it again. If the user inputs Y ... the program will loop it back to the beginning and run the entire program again. If the user inputs N, it exits.
import java.util.Scanner; // show them as code
public class HowToDoLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
Upvotes: -4
Views: 29912
Reputation: 1
Scanner sc = new Scanner(System.in);
String response = "";
do {
System.out.println("Enter your marks");
float marks = sc.nextFloat();
if (marks > 90 && marks <= 100) {
System.out.println("You have scored A grade");
} else if (marks > 80 && marks <= 90) {
System.out.println("You have scored B grade");
} else if (marks > 70 && marks <= 80) {
System.out.println("You have scored C grade");
} else if (marks > 60 && marks <= 70) {
System.out.println("You have scored D grade");
} else if (marks > 50 && marks <= 60) {
System.out.println("You have scored E grade");
} else {
System.out.println("You have failed");
}
System.out.println("do you want to continue y or n?");
response = sc.next();
}while(response.equalsIgnoreCase("y"));
}
Upvotes: 0
Reputation: 1104
String c = "";
do{
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
c = input.nextLine();
}while(c.equalsIgnoreCase("Y"));
Upvotes: 1
Reputation: 1710
while(true){
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
String c = input.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}//else continue to loop on any string ;-)
}
Upvotes: 2