Java 布尔值未设置为 true



我的代码接受用户输入的字符串并返回单词数以及第一个单词。当用户输入空字符串时,我不希望显示"您的字符串中有 x 个单词"或"第一个单词是 x",所以我创建了一个booleanboolean没有在我尝试设置的方法中设置它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;
}
}

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

  • 首先:你不需要empty变量
  • 您可以通过调用getWordCount方法知道"word"是否为空,并将结果存储在变量中 (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;
}

你只需要改变位置,如果为了可变可见性。

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 (str != null && str.length() == 0) {
System.out.println("ERROR - string must not be empty.");
empty = true;
}
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 (!(" ".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;
}

如果您确实想使用布尔值,请尝试使用 string 参数创建一个布尔方法,该方法仅在字符串不为空时才返回 true,然后将布尔返回类型分配给empty布尔变量。

相关内容

最新更新