【问题标题】:Program doesn't seem to enter while程序似乎没有进入 while
【发布时间】:2015-11-14 11:22:41
【问题描述】:

我正在尝试制作一个输入硬币值以提供门票的程序,但它似乎没有进入第一次,当我首先运行它时它不接受双打(例如 0.1或 0.5),无论您输入什么数字,它都显示这是您的票,结束!代码有什么问题?

import acm.program.*;

public class tickets extends ConsoleProgram {
    public static double eisitirio = 1.2;
    public void run(){
    double nomisma=readInt("Insert coins and then press 0: ");
    boolean synthiki=false;
    double poso=0;
    while (synthiki=false){
        while (nomisma != 0){
            if ((nomisma==0.1)||(nomisma==0.2)||(nomisma==0.5)||(nomisma==1)||(nomisma==2)||(nomisma==5)){
            poso=poso+nomisma;
            }else {
                System.out.println("You did not insert a supported coin, please insert another one");
            }
            nomisma=readInt("Insert coins and then press 0: ");
        }
        if (poso < eisitirio){
            System.out.println("You did not insert enough money, please insert more coins");
        }else {
            synthiki=true;
        }
    }
    println("Here is your ticket");
    poso=poso-eisitirio;
    if ((poso/5) > 0){
        println("You have change: 5 euros");
        poso = poso-5;
    }
    if ((poso/2) > 0){
        println("You have change: 2 euros");
        poso = poso-2;
    }
    if ((poso/1) > 0){
        println("You have change: 1 euros");
        poso = poso-1;
    }   
    if ((poso/0.5) > 0){
        println("You have change: 50 cents");
        poso = poso-0.5;
    }
    if ((poso/0.2) > 0){
        println("You have change: 20 cents");
        poso = poso-0.2;
    }
    if ((poso/0.1) > 0){
        println("You have change: 10 cents");
        poso=poso-0.1;
    }
    }

}

【问题讨论】:

  • 尝试使用 '==' 而不是 '='。一等于分配,二等于检查相等。

标签: java logic


【解决方案1】:

比较应该使用“==”,而不是“=”(assignment)。改变

while (synthiki=false)

while (synthiki == false)

【讨论】:

    【解决方案2】:

    = 是赋值运算符。它将右侧表达式的值分配给左侧变量,并返回它。如果你想检查是否相等,你应该使用== 操作符:

    while (synthiki == false) {
    

    或者更好的是,因为它是一个布尔变量,所以不要将它的值与文字进行比较,而是直接计算它:

    while (!synthiki) {
    

    【讨论】:

      【解决方案3】:

      你的条件,

      while (synthiki=false){...}
      

      应该是,

      while (!synthiki){...}
      

      第一个条件将false 分配给synthiki。由于synthikiboolean,因此您可以直接在while() {...} 中使用变量。此外,如果您必须检查synthiki 的值,请使用== 而不是=

      点赞:while(synthiki == false) {...}

      【讨论】:

        猜你喜欢
        • 2013-11-16
        • 2015-07-26
        • 2013-01-13
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多