当我按下时,有人可以解释如何输入结束。因为我只是一个初学者,所以无需按下输入并计算长度而没有太多高级的东西。
class UserInput//defines class
{//class begins
public static void main (String[] args) throws IOException
{//main method begins
BufferedReader bf = new BufferedReader(newInputStreamReader(System.in));
//tells the user what the program does
System.out.println("This program will give you the total number of inputed characters.");
// tells the user how to end the program
System.out.println("To obtain your final number of characters, enter .");
System.out.println("");
//tells user to type in characters
System.out.println("Enter any characters you want:");
String input = bf.readLine(); //reads the user input and initializes input
//initialize and declares variables
int length = 0;
length = length + anything.length();
//outputs total number of characters
System.out.println("The total number of characters input is " + length);
}//main method ends
}//class ends
答案 0 :(得分:1)
尝试使用System.in.read()
通过char读取char。如果这不适用于您的平台,请参阅Why can't we read one character at a time from System.in?
答案 1 :(得分:0)
使用“。”结束命令不是惯例。在命令行程序上。我建议您使用输入或制作图形用户界面,在使用文档侦听器或等效文件将其键入textarea时对字母进行计数。 GUI解决方案现已在此处提供:sample project showing it working。
答案 2 :(得分:0)
您可以尝试这样的事情:
Scanner input = new Scanner(System.in);
int totalChars = 0;
// start an endless loop, constantly reading the next entered char from the user
while (true) {
String next = input.next();
if (".".equals(next)) {
// when the user enters ".", exit the loop and stop reading
input.close();
break;
} else {
// otherwise, just increment the total chars counter
totalChars++;
}
}
System.out.println("Total characters: " + totalChars);
基本思想是继续通过char读取char,直到用户选择以"来终止。"命令。我建议您将BufferedReader
替换为Scanner
。 Scanner
类更适合阅读用户输入,提供更自然且易于使用的界面,并将帮助您充分实现目标。