Use Scanner to read user input : Scanner « Development Class « Java






Use Scanner to read user input

  
import java.util.Scanner;

class Console {

  static Scanner sc = new Scanner(System.in);

  public static boolean askYorN(String prompt) {
    while (true) {
      String answer;
      System.out.print("\n" + prompt + " (Y or N) ");
      answer = sc.next();
      if (answer.equalsIgnoreCase("Y"))
        return true;
      else if (answer.equalsIgnoreCase("N"))
        return false;
    }
  }
}

public class MainClass {
  public static void main(String[] args) {
    while (Console.askYorN("Keep going?")) {
      System.out.println("!");

    }
  }
}

   
  








Related examples in the same category

1.Read int by using Scanner Class
2.Count all vowels inputed from keyboard
3.Use Scanner to compute an average of the values
4.Use Scanner to compute an average of the values in a file
5.Use Scanner to read various types of data from a file
6.Use Scanner to compute an average a list of comma-separated values
7.Demonstrate findInLine()
8.use Scanner to read input that contains several different types of data
9.Letting the user decide when to quit
10.Test the input string in the while condition.
11.This program demonstrates console input.
12.Reading double value from console with ScannerReading double value from console with Scanner