第一篇文章和所有这些.我是新手程序员.
无论如何,我的任务是创建一个Java程序,它将以句子和单词的形式接受用户输入.该程序从句子中删除空格,并检查该单词是否出现在“无空白”句子中.但是,该程序还会从单词的末尾删除一个字母,并检查该单词是否出现在无空白句子中.该程序继续删除该单词中的字母,直到没有更多的字母要删除.
此外,程序还应该说明单词的位置,但不能多次列出一个位置.如果程序找不到整个单词,则打印出“未找到’Word’.”如果是,则打印出”Word’在位置’x’处找到“
例如如果我的句子是“她在河边唱歌”并且字是“字节”,那么代码应该检查“shesingsbytheriver”中的“byte”,“byt”,“by”和“b”,但它找不到“byt”,“by”和“b”位于同一位置.
以下是我的代码.一切都很好,直到我的if语句.它没有找到空白句子中的单词,而是继续打印出“未找到’Word’.”
最后几点说明:我应该避免使用数组,我需要的大多数命令都是String类.
谢谢!
// The purpose of this program is to take in user input in the form
// of a sentence and a word. The program repeats the sentence and word
// back, removes the spaces, and checks if the word was present in the
// sentence. The program removes a letter from the word, checks if that
// "word" is present and continues until it cannot remove any more letters.
import java.util.*;
import javax.swing.JOptionPane;
public class Program1 {
public static void main(String[] args) {
String sentenceBlankless;
String sentence = JOptionPane.showInputDialog("Please enter a sentence: ");
String word = JOptionPane.showInputDialog("Please enter a word: ");
sentenceBlankless = sentence.replaceAll(" ", "");
JOptionPane.showMessageDialog(null, "The original imput is: " + sentence);
JOptionPane.showMessageDialog(null, "Removing blanks - " + sentenceBlankless);
JOptionPane.showMessageDialog(null, "Input word - " + word);
for (int x = 0; x < word.length(); x++) {
if (sentenceBlankless.toLowerCase().contains(word.toLowerCase())) {
int loc = sentence.toLowerCase().indexOf(word.toLowerCase());
JOptionPane.showMessageDialog(null, word.substring(0, word.length() - x) + " was found at location " + loc);
} else {
JOptionPane.showMessageDialog(null, word.substring(0, word.length() - x) + " was not found");
}
}
}
}