首页 > 解决方案 > Java布尔值未设置为true

问题描述

我的代码采用用户输入的字符串并返回单词数以及第一个单词。当用户输入一个空字符串时,我不希望显示“您的字符串中包含 x 个单词”或“第一个单词是 x”,因此我创建了一个boolean但未在boolean我尝试将其设置为的方法中设置true在。我能得到的关于为什么或如何解决它的任何帮助都会很棒。谢谢!

public static void main(String[] args){
    boolean empty = false;
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String str = in.nextLine();

    if (empty == false) {
        System.out.println("Your string has " + getWordCount(str)+" words in it.");
        System.out.println("The first word is: " + firstWord(str));
    }
}

public static String firstWord(String input) {

    for(int i = 0; i < input.length(); i++)
    {
        if(input.charAt(i) == ' ')
        {
            return input.substring(0, i);
        }
    }

    return input; 
}    

 public static int getWordCount(String str){
       int count = 0;

       if(str != null && str.length() == 0){ 
           System.out.println("ERROR - string must not be empty.");
           empty = true;
       }

       else if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))){

            for (int i = 0; i < str.length(); i++){

                if (str.charAt(i) == ' '){
                    count++;
                }
            }
            count = count + 1; 
        }
    return count;
    }
 }

标签: javaeclipseboolean

解决方案


你必须在这里重新考虑你的逻辑(见下面的片段):

  • 首先:你不需要empty变量
  • 您可以通过调用该方法来知道“单词”是否为空,getWordCount并将结果存储在变量(wordCount?)中。然后你可以通过做检查是否至少有一个词wordCount > 0

片段:

    public static void main(String[] args){
        // boolean empty = false;           // --> not needed
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = in.nextLine();
        final int wordCount = getWordCount(str);

        if (wordCount > 0) { // show message only if there is at least one word
            System.out.println("Your string has " + wordCount +" words in it.");
            System.out.println("The first word is: " + firstWord(str));
        }
    }

    public static String firstWord(String input) {
        // .. code omitted for brevity
    }

    public static int getWordCount(String str){
        int count = 0;

        if(str != null && str.length() == 0){
            System.out.println("ERROR - string must not be empty.");
            // empty = true; -->  not needed
        }

        // ... code omitted for brevity
        return count;
    }

推荐阅读