2

所以我的代码是用于家庭作业,用户输入一个句子(字符串),我需要搜索字符串并返回最小的单词。但是,必须在字符串的第一个位置输入一个数字。例如:“4 这是什么”。输出应为“IS”并忽略数字。我想出如何忽略数字的唯一方法是让循环跳过数字所在的第一个位置。它本身就可以工作,但是每当我将其放入程序的其余部分时,它就会停止工作。反正有没有让这个程序更干净?

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    // Lexicographically smallest word
    String TheSentence = sc.nextLine();
    String[] myWords = TheSentence.split(" ");
    int shortestLengths, shortestLocation;
    shortestLengths = (myWords[1]).length();
    shortestLocation = 1;
    for (int i = 1; i < myWords.length; i++) {
        if ((myWords[i]).length() < shortestLengths) {
            shortestLengths = (myWords[i]).length();
            shortestLocation = i;
        }
    }
    System.out.println(myWords[shortestLocation]);
}
4

4 回答 4

1

在你的for循环内(应该从 开始i = 0),添加如下代码:

try {
  double value = Double.parseDouble(myWords[i]);
} catch (NumberFormatException e) {
  // add the rest of your code here
}

这个想法是您尝试将单词转换为数字,如果失败,则表示它不是数字,因此您可以在单词上使用长度逻辑。

于 2012-09-09T19:51:10.190 回答
0

您应该做的第一件事是创建您想要使用的函数,而不是将练习的相关代码与从输入流中读取一行等内容混合在一起。

您可以使用 测试字符是否为字母Character.isLetter(char)String.charAt(int)一个好的练习是仅使用该函数构建一个解决方案,并在循环中分别查看每个字符(方法)。解决方案是记住当前最短的单词从哪里开始以及它有多长。


在实践中,我只会使用这样的正则表达式:

public static String shortestWord(String sentence) {
  String shortest = null;
  Pattern word = Pattern.compile("\\w+");
  Matcher m = word.matcher(sentence);
  while (m.find()) {
    String candidate = m.group();
    if (shortest == null || shortest.length() > candidate.length())
      shortest = candidate;
  }
  return shortest;
}
于 2012-09-09T20:08:57.320 回答
0

您可以尝试使用子字符串,例如

String result=inputString.substring(1)

'1' 是字符串中的第二个字母,子字符串返回除第一个之外的每个值。

于 2012-09-09T20:14:34.377 回答
0

下面基本上只是缩短了您的代码..除此之外它没有太大变化。话虽如此..在一个名为 shortestWord() 或其他东西的方法中创建所有这些会更好。下面的代码确实没有理由不工作。

修改后的代码:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String[] myWords = (sc.nextLine()).split(" ");
    int shortestLocation = 1
    for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
                                               // already made shortestLocation = 1
        if (myWords[i].length() < myWords[shortestLocation].length()) {
            shortestLocation = i;
        }
    }
    System.out.println(myWords[shortestLocation]);
}

建议代码:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String[] myWords = (sc.nextLine()).split(" ");
    System.out.println("The shortest word is: " + shortestWord(myWords));
}

public static String shortestWord(String[] myWords) {
    int shortestLocation = 1
    for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
                                               // already made shortestLocation = 1
        if (myWords[i].length() < myWords[shortestLocation].length()) {
            shortestLocation = i;
        }
    }
    return myWords[shortestLocation];
}
于 2012-09-15T06:27:10.230 回答