【问题标题】:if else statements returning null with boolean operatorif else 语句使用布尔运算符返回 null
【发布时间】:2015-01-07 02:27:03
【问题描述】:

这是我第一次提出问题,所以我不确定我的标题是否正确,因为我对 java 还很陌生......基本上我的程序在 changeNameFormat 方法期间返回所有 null 时没有名称中有空格,但我想要它做的是打印出“你的名字中没有空格”,然后转到下一个方法。目前我的代码如下,至少在逻辑上对我来说是有道理的,但我不是专家。

import java.util.*;

public class Lab11 {

    static String name, first, last, word;
    static boolean space;

    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input your name: ");
        name = input.nextLine();
        changeNameFormat();
        if (space = true) {
            System.out.println("Your name is : " + first + " " + last);
            System.out.println("Your first name is : " + first);
            System.out.println("Your last name is : " + last);
        }
        else {
            System.out.println("Your name contains no spaces");
        }
        System.out.println("Input word for palindrome test: ");
        word = input.nextLine();
        if (palindrome(word)) {
            System.out.println(word + " is a palindrome");
        }
        else {
            System.out.println(word + " is NOT a palindrome");
        }
    }

    public static void changeNameFormat() {
        if (name.contains(" ")) {
            String [] split = name.split(" ", 2);
            first = split[0];
            String last = split[1];
            space = true;
        }
        else {
            space = false;
        }
    }

    public static boolean palindrome(String w) {
        System.out.println("Checking if " + word + " is a palindrome.");
        System.out.println("... Loading...");
        String reverse = "";
        for (int i = w.length() - 1 ; i >= 0 ; i--) {
            reverse = reverse + w.charAt(i);
        }
        if (w.equalsIgnoreCase(reverse)) { // case insensitive check
            return true;
        }
        else {
            return false;
        }
    }
}

【问题讨论】:

    标签: java if-statement boolean boolean-logic


    【解决方案1】:

    一个非常小的疏忽。

    您使用了一个等于赋值运算符 (=),它将 true 分配给 space。如果要检查空格是否为真,则需要双等比较运算符(==):

    if (space == true)
    

    请注意,更好、更惯用的写法是:

    if (space)
    

    如果您没有注意到,您的 ChangeNameFormat() 方法也会本地化 last 变量。

    【讨论】:

    • 非常感谢 :) 不敢相信我没听懂
    猜你喜欢
    • 2014-12-19
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2022-01-09
    • 2020-08-20
    • 2022-07-28
    • 2021-08-31
    相关资源
    最近更新 更多