文字不打印

时间:2013-09-07 15:11:27

标签: java

在学校,我不得不制作一个计算器程序。在程序中,我们询问用户是否要添加,减去,乘以或除。最后,我们询问用户他们想继续该计划还是否。我还没有放入循环部分,但我的问题是,在显示“你想继续”之后,程序就会退出。

package calculator;

import java.util.Scanner;

public class calculator {

    public static void main(String[] args) {

        {

        int o1; //first operand
        int o2; //second operand

        Scanner input = new Scanner (System.in);
        System.out.println("Enter a choice:");
        System.out.println("+ to add");
        System.out.println("- to subtract");
        System.out.println("* to multiply");
        System.out.println("/ to divide");
        System.out.println("X to exit");
        String userChoice = input.nextLine();

        if (userChoice.equals("X to exit")) {
            System.exit(0);
        }

        System.out.println("Enter the first operand:");
        o1 = input.nextInt();
        System.out.println("Enter the second operand:");
        o2 = input.nextInt();

        if (userChoice.equals("+ to add")) {
            System.out.println( (o1) + (o2) ); }
            else if (userChoice.equals("- to subtract")) {
                System.out.println( (o1) - (o2) ); }
            else if (userChoice.equals("* to multiply")) {
                System.out.println( (o1) * (o2) ); }
            else if (userChoice.equals("/ to divide")) {
                System.out.println( (o1) / (o2) ); }

        System.out.println("Would you like to continue?");
        System.out.println("Yes");
        System.out.println("No");
        String userPick = input.nextLine(); {

        if (userPick.equals("Yes")) {
            System.out.println("Ok."); }
            else if (userPick.equals("No")) {
                System.exit(0); }

        }
        }
        }

        // TODO Auto-generated method stub


}

4 个答案:

答案 0 :(得分:0)

试试这个:

 Scanner input = new Scanner (System.in);
 while(true){
    System.out.println("Enter a choice:");
    System.out.println("+ to add");
    ......
    if (userPick.equals("Yes")) {
        System.out.println("Ok."); }
        else if (userPick.equals("No")) {
            System.exit(0); }

    }
 }

它将继续循环逻辑,直到满足终止条件。您可能还想在System.exit()之前关闭扫描仪;事实上,在任何终止之前。

答案 1 :(得分:0)

您可以在代码前添加一行

String userPick = input.nextLine();哪一行是input.nextLine();

它可以很好地工作,可以接收输入断行。你可以尝试。

ps:我的英语不好,我不确定我是否表达清楚。

答案 2 :(得分:0)

System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
// add this lline, it can make a difference
input.nextLine();
String userPick = input.nextLine();

答案 3 :(得分:0)

您需要在程序中要重新启动的位置while(true) {}循环。这样,如果用户说“是”,您可以返回到开头,但如果用户拒绝,程序将退出。

相关问题