打印if和else循环的布尔输出

时间:2016-02-01 03:10:16

标签: java boolean

我有一个用于检查键盘输入的Java代码。 如果特定字符返回True,则有一个循环。 对于任何其他角色,else返回false。

如何编写一个代码,用于识别程序选择上述两个(True或False)中的哪一个并打印出来? 实例connectionStatus

的布尔值
import java.util.Scanner;

public class BlueTooth3 {
    public boolean connectionStatus;

     boolean connectBlueTooth () {
        System.out.println("Enter connecting code Baby3");
        Scanner keyboard = new Scanner(System.in);
        String conCode = keyboard.next();
        System.out.println("You Entered " + conCode);
        keyboard.close();
        if (conCode.equals ("c")){
        System.out.println(conCode + " Is a true Code");
        System.out.println("This is Boolean " +Boolean.TRUE);

            return connectionStatus;
        } 

        if (conCode.equals ("C")){
            System.out.println(conCode + " Is a true Code");
            System.out.println("This is Boolean " +Boolean.TRUE);

                return connectionStatus;
            }
        else {
            System.out.println( conCode + " Is a false Code" );
            System.out.println("This is Boolean " + Boolean.FALSE);
            return connectionStatus;
        }
        }
     }

1 个答案:

答案 0 :(得分:0)

除非我闭上眼睛,否则你似乎没有对connectionStatus变量做任何事情。您可以更改该变量的值,以便接收该变量的函数可以相应地执行操作。例如:

    if (conCode.equals ("C")){
        System.out.println(conCode + " Is a true Code");
        System.out.println("This is Boolean " +Boolean.TRUE);
        connectionStatus = true; // means that the code went in this if
            return connectionStatus;
    }
    else {
        System.out.println( conCode + " Is a false Code" );
        System.out.println("This is Boolean " + Boolean.FALSE);
        connectionStatus = false; // means that the code went in this else
        return connectionStatus; 
    }

你的代码应该是这样的:

public void myFunc(){
    System.out.println(connectBlueTooth);
}

这只是简单地打印出connectBlueTooth函数的结果,如果它进入if则该结果为True,如果进入else则为False。