【问题标题】:My program compiled, but the terminal won't show up (BlueJ) [closed]我的程序已编译,但终端不会显示(BlueJ)[关闭]
【发布时间】:2022-11-01 11:14:09
【问题描述】:

我之前在这里看到过类似的问题 (BlueJ - My program compiles with no errors but doesn't run),但在这种情况下,解决方案是 System.out.println() 在获得输入以强制终端打开之前,但这里不起作用。当我尝试运行程序时,什么也没有发生,没有终端,没有错误,什么都没有。我在初始化扫描仪对象的行之前有打印语句,因此我从上述帖子中排除了解决方案。

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        String cont="";
        while(cont.equals("y"))
        {
            int answer_int=0;
            String answer_string="";
            System.out.println("Enter the operation that you would like to perform (+,-,*,/)");
            Scanner scan=new Scanner(System.in);
            String operation=scan.nextLine();
            ......
            //answer_int is converted to a Binary String and assigned to answer_string
            answer_string=java.lang.Integer.toBinaryString(answer_int);
            System.out.println(answer_string);
            System.out.println("Do you want to continue running this program? Press y or n.");
            Scanner go = new Scanner(System.in);
            cont=go.nextLine();
        }
    }
}

【问题讨论】:

    标签: java java.util.scanner bluej


    【解决方案1】:

    您正在用空字符串初始化cont 变量,并且在下一行循环条件是cont == y。该条件不会评估为true,因此您的循环不会执行。另外,对于Strings,我们通常使用equals 方法,因为== 运算符不会比较Strings 的内容。

        String cont="";
        while(cont=="y") // cont is empty string, cont == "y" will evaluate false
    

    使用以下内容:

        String cont="y";
        while(cont.equals("y"))
    

    【讨论】:

    • 我在while循环之外初始化了cont,除非用户输入了不同的值,否则循环运行时值不应该改变。
    • @Hydrolox3552 但如果cont=="" 使用您当前的循环条件,循环甚至不会开始运行。您要么必须将 cont 初始化为某个值,要么更新 while 循环条件以开始在 cont.isEmpty() 上工作
    • 对不起,我应该看到的
    猜你喜欢
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多