我希望在命令提示符下以这种方式输入原始问题(rawQuestions): java Hangman Hello测试123,进入数组(问题)。我知道rawQuestion不能在"存储有效问题到数组"部分因为
在
行因此我该如何重写呢?
public class Hangman {
//Validation of raw questions
public static boolean isValidQuestion(String rawQuestion){
rawQuestion = rawQuestion.toUpperCase();
boolean vQuestion = true;
for(int i=0; i<rawQuestion.length(); i++){
char c = rawQuestion.charAt(i);
if(!(c>='A' && c<='Z'))
vQuestion = false;
}
return vQuestion;
}
public static void main(String args[]){
boolean vQs[] = new boolean[args.length];
for(int i=0; i<args.length; i++){
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if(b)
System.out.println(rawQuestion + " is a valid question!");
else
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
vQs[i] = b;
}
//count the number of valid questions
int vCount = 0;
for(int i=0; i<vQs.length; i++){
System.out.println(i + " " + vQs[i] );
if(vQs[i])
vCount++;
}
System.out.println("There are " + vCount + " valid questions");
//store valid questions into an array
String questions[] = new String[vCount];
for(vCount=0; vCount<args.length; vCount++){
questions[vCount] = String rawQuestion;
System.out.println( questions[vCount] );
}
}
}
答案 0 :(得分:1)
试试这个:
String[] validQuestions = Arrays.stream(args)
.filter(Hangman::isValidQuestion)
.toArray(String[]::new);
int validQuestionCount = validQuestions.length;
但即使没有Streams,您的整个方法也可以在一个for循环中完成,一次计算和收集有效问题,而不是分三个步骤:
List<String> validQuestions = new ArrayList<>();
for (int i = 0; i < args.length; i++)
{
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if (b)
{
validQuestions.add(rawQuestion);
System.out.println(rawQuestion + " is a valid question!");
}
else
{
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
}
}
// count the number of valid questions
System.out.println("There are " + validQuestions.size() + " valid questions");
// store valid questions into an array
String questions[] = validQuestions.toArray(new String[validQuestions.size()]);
这样,您不必自己处理索引变量,这很难理解,特别是如果其他人试图阅读它。 (特别是vCount
的重用对我来说有点可怕)