我一直在寻找一种通过方法加载输入的方法,以便用户可以操作菜单。
到目前为止,我有这个:
public static char printMenu(){
char option = ' ';
Scanner load = new Scanner(System.in);
System.out.println("\nMENU\nc - blah blah blah");
option = load.next().charAt(0);
System.out.println(option);
return option;
}
但是当我在这里打电话时:
System.out.println("You entered: "+storage);
char menuOpt = ' ';
while(menuOpt != 'q'){
menuOpt = printMenu();
并输入字母c然后输入q。它给了我:
You entered: Hello my name is Kong.
MENU
blah blah blah
Choose an option:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at AuthoringAssistant.printMenu(AuthoringAssistant.java:10)
at AuthoringAssistant.main(AuthoringAssistant.java:36)
我认为,因为它是一个char返回类型,我可以使用它吗?我清楚地看到我错了。我在俯瞰什么?
谢谢。
对于Aify:
import java.util.Scanner;
public class AuthoringAssistant {
public static char printMenu(){
char option = ' ';
Scanner load = new Scanner(System.in);
System.out.println("\nMENU\nc - Number of non-whitespace characters\nw - Number of words\nf - Find text\nr - Replace all !'s\ns - Shorten spaces\nq - Quit\n\nChoose an option:");
option = load.nextLine().charAt(0);
System.out.println(option);
return option;
}
public static int getNumOfNonWSCharacters(String storage){
int n = 0;
int amount = 0;
for(n=0;n<storage.length();++n){
if(storage.charAt(n) != ' '){
++amount;
}
}
return amount;
}
public static void main(String[] args) {
String storage = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sample text:");
storage = scan.nextLine();
System.out.println();
System.out.println("You entered: "+storage);
char menuOpt = ' ';
while(menuOpt != 'q'){
menuOpt = printMenu();
if(menuOpt == 'c'){
int amount = getNumOfNonWSCharacters(storage);
System.out.println("Number of non-whitespace characters: "+amount);
}
}
return;
}
}