Question:
I have a program that does some calculations for the user and at the end there is a out statment that says. "would you like to run the program again?" I'd like the user to able to input yes or no.
Answer:
Use a while() loop and either break out or run again after the response from the scanner input.
Code:
import java.util.*; public class RunAgain { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("Doing stuff...."); System.out.print("Run again: "); String input = sc.nextLine(); if(! input.equals("yes")){ break; } } System.out.println("Goodbye"); } }
Output:
$ java RunAgain Doing stuff.... Run again: yes Doing stuff.... Run again: yes Doing stuff.... Run again: no Goodbye