java - Scanner accepts wrong input
问题描述
public static String userInput(){
Scanner sc = new Scanner(System.in);
System.out.println("Please type in a word in small letters to be encrypted:");
String input = sc.nextLine();
boolean loopChecker = false;
while(!loopChecker){
if (inputChecker(input)){
loopChecker = true;
}
else if (!loopChecker){
System.out.println("You typed " + input + ".");
System.out.println("Please type a small word to be encoded.");
input = sc.nextLine();
}
}
return input;
}
Using the string input from above as argument to the following method loops to check if the user has entered the desired input (letters in the danish alphabet):
public static boolean inputChecker(String message){
String alphabet = "abcdefghijklmnopqrstuvwxyzæøå";
boolean loopChecker = true;
for (int i = 0; i < message.length(); i++) {
for (int j = 0; j < message.length(); j++) {
String messageIndex = Character.toString(message.charAt(j));
if(!alphabet.contains(messageIndex)){
loopChecker = false;
}
}
}
return loopChecker;
}
The problem is as following: sc.nextLine() accepts "Enter" as valid input when the user hits enter on the keyboard. Why is this? It should only accept the letters in the string "alphabet". How do I work around this problem?
解决方案
You need to test for the empty String
. You do not need a nested loop on message
. And you could simplify inputChecker
by removing the temporary local variable. Something like,
public static boolean inputChecker(String message) {
if (message.isEmpty()) {
return false;
}
String alphabet = "abcdefghijklmnopqrstuvwxyzæøå";
for (int i = 0; i < message.length(); i++) {
if (alphabet.indexOf(message.charAt(i)) < 0) {
return false;
}
}
return true;
}
推荐阅读
- sql - 将许多大文件从 R 复制到新的 SQL 数据库
- prolog - Prolog 术语:id(X,X)。事实还是规则?
- excel - 使用具有两个条件的 COUNTIFS?
- php - 代码在 PHP 7.3 中无法正常运行。修复与 PHP 7.1 和 7.2 向后兼容的最佳方法,count() 错误
- reactjs - React-admin 表显示两次
- javascript - TypeError:解析器不是函数
- docker - Kubernetes 集群“cni 配置未初始化”
- pandas - GroupBy 聚合基于条件和使用 pandas 的年度总和
- charts - QML:ChartView 系列的自定义可拖动点委托
- php - 编写一个基本的 php 脚本