java - 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;
}
}
解决方案
你必须在这里重新考虑你的逻辑(见下面的片段):
- 首先:你不需要
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;
}
推荐阅读
- python - 无法通过 instabot 将某些照片上传到 instagram
- sql - SUM SQL - 按年份选择使用/分组
- html - 改进@font-face url 以提高性能
- rust - 将大小为 N 的向量转换为固定大小的数组长度 N 超过 32
- java - 需要单个 bean,但在简单的 spring-boot 应用程序中找到了 2 个
- angular - 如何从 ng-template 中检索组件实例?
- java - 如何从 Spring Boot @Controller 返回 json/xml?
- python - 在生产 Django-Heroku 中找不到媒体文件:返回 404 错误
- android - Jetpack Compose 应用程序无法在 AVD 上启动
- c - 如何修复树莓派 4 上的 exec 格式错误