【发布时间】:2018-10-15 11:38:57
【问题描述】:
我正在上初级编码课程,这是我的作业: 编写一个名为 palindromeCheck 的 void 方法,它不接受任何参数。该方法应该具有检查单词是否是回文并将所有回文打印到屏幕上的功能,每行一个。此外,输出的最后一行应该有消息:“There are x palindromes out of y words provided by user”(其中 x 是检测到的回文词数,y 是用户输入的词总数)。提示:对于本实验练习,您将需要对 String 对象使用以下方法:length() 给出字符串的长度(即它包含的字符数)和 charAt(i) - 给出位置 i 处的字符。 由于输入的输入应该由空格分隔,我对如何创建每个输入的单词进行迭代的 while 循环感到困惑。我的教授以她希望我们创建的方法的骨架形式帮助我们。在那个骨架中有一个 while 循环,它对输入的每个单词执行操作
while (keyboard.hasNext()){
someWord = keyboard.next();
// some code that performs actions
}
这个 while 循环可以工作,但在它完成并应该终止后,它只会提示输入更多输入。下面是我当前的代码,除了这个逻辑错误之外应该完成。
public static void palindromeCheck(){
String someWord = ""; // Stores words read from user input
int count = 0; // keeps track of Palindrome words only
int total = 0; // Counts the total number of lines read from the given text file
int score = 0; // used as a condition to count palindrome words
System.out.println("Enter some words separated by white space.");
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) { // for each word user enters
someWord = keyboard.next(); // store each word in a string variable and then do operations
score = 0;
int n = (someWord.length()-1);
for (int i = 0; i < (someWord.length()-2); i++){
for (int j = (someWord.length()-1); i < (someWord.length()-2); j--){
j = n;
n--;
if(someWord.charAt(i) == someWord.charAt(j)){
break;
}
else
score++;
}
}
if(score == 0){ // if word is palindrome adds to counter
count++;
}
total++; // increment number of words as you read each one
//System.out.println(" " + total + " " + someWord); // test
}
System.out.println("There are " + count + " palindromes out of " + total + " words provided by user.");
}
【问题讨论】:
-
你能发布你的主要方法吗?
-
什么时候终止?
-
@m0skit0
import java.util.Scanner; public class Lab5 { public static void main (String [] args) { palindromeCheck(); } -
@shmosel 循环应该在用户输入的所有单词都被读取后终止。
-
@sinclair 我不明白你的意思,一切都在与操纵字符串有关的循环中,我只在 main 中调用 palindromeCheck() 一次
标签: java input while-loop logic palindrome