使用scanner.nextLine()
import java.util.Scanner;class TestRevised { public void menu() { Scanner scanner = new Scanner(System.in); System.out.print("Enter a sentence:\t"); String sentence = scanner.nextLine(); System.out.print("Enter an index:\t"); int index = scanner.nextInt(); System.out.println("\nYour sentence:\t" + sentence); System.out.println("Your index:\t" + index); }}
例1:String sentence = scanner.nextLine();
System.out.print("Enter an index:\t");
.
Enter a sentence: Hello.Enter an index: 0Your sentence: Hello.Your index: 0
// Example #2import java.util.Scanner;class Test { public void menu() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nMenu Options\n"); System.out.println("(1) - do this"); System.out.println("(2) - quit"); System.out.print("Please enter your selection:\t"); int selection = scanner.nextInt(); if (selection == 1) { System.out.print("Enter a sentence:\t"); String sentence = scanner.nextLine(); System.out.print("Enter an index:\t"); int index = scanner.nextInt(); System.out.println("\nYour sentence:\t" + sentence); System.out.println("Your index:\t" + index); } else if (selection == 2) { break; } } }}
例2:String sentence = scanner.nextLine();
System.out.print("Enter an index:\t");
.
Menu Options(1) - do this(2) - quitPlease enter your selection: 1Enter a sentence: Enter an index:
繁星点点滴滴
慕雪6442864
相关分类