簡體   English   中英

文字無法列印

[英]Text not printing

在學校,我不得不做一個計算器程序。 在程序中,我們詢問用戶是否要加,減,乘或除。 最后,我們要求他們的用戶繼續該程序或否。 我還沒有放入循環部分,但是我的問題是在顯示“您想繼續嗎”之后,程序就退出了。

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


}

嘗試這個:

 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()之前關閉掃描儀。 並且在任何實際終止之前。

您可以在代碼之前添加一行

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

它可以正常工作,可以接收輸入中斷線。您可以嘗試。

ps:我的英語不好,我不確定我說得很清楚。

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();

您需要在程序中希望重新啟動的地方進行while(true) {}循環。 這樣,如果用戶說“是”,則可以返回到開頭,但是如果用戶說“否”,則程序將退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM