如果语句在while循环中不起作用

时间:2014-12-13 03:35:52

标签: java if-statement while-loop

这是我的第一篇文章,对于您可能遇到的任何误解感到抱歉,我用C ++制作了这个计算器,它工作得非常好,所以我决定用java编写它。当我运行程序时,它没有给我任何错误,但我的while循环中的if语句不起作用

import java.util.Scanner;

public class ohmlaw 
{
    public static void main(String args[])
 {
    float current;
    float resistance;
    float voltage;
    String calchoice = new String();
    Scanner cc = new Scanner(System.in);
    System.out.println("OHMCAL, OHM'S LAW CALCULATOR BY RASHAAD BRYAN");
    System.out.println();
    System.out.println();
    System.out.println();
    System.out.println("Instructions");
    System.out.println("If you want to calculate the voltage type voltage");
    System.out.println("If you want to calculate the current type current");
    System.out.println("If you want to calculate the resistance type resistance");
    System.out.println("If you want to stop the program type stop");
    System.out.println();
    System.out.println();
    System.out.println();
    System.out.print("Please enter calculation choice ");
    calchoice = cc.nextLine();
    System.out.println();
    while (calchoice != "stop")
    {
        if (calchoice == "current")
        {
            System.out.print("Please enter voltage (V) ");
            voltage = cc.nextFloat();
            System.out.println();
            System.out.print("Please enter resistance () ");
            resistance = cc.nextFloat();
            System.out.println();
            current = voltage/resistance;
            System.out.println("The current is = " + current  + "A");
            System.out.println();
        }
        if (calchoice == "voltage")
        {
            System.out.print("Please enter current (V) ");
            current = cc.nextFloat();
            System.out.println();
            System.out.print("Please enter resistance () ");
            resistance = cc.nextFloat();
            System.out.println();
            voltage = current * resistance;
            System.out.println("The voltage is = " + voltage  + "V");
            System.out.println();
        }
        if (calchoice == "resistance")
        {
            System.out.print("Please enter Voltage (V) ");
            voltage = cc.nextFloat();
            System.out.println();
            System.out.print("Please enter current (I) ");
            current = cc.nextFloat();
            System.out.println();
            resistance = voltage/current;
            System.out.println("The resistance is = " + resistance  + "");
            System.out.println();
        }
        System.out.print("Please enter calculation choice ");
        calchoice = cc.nextLine();
        System.out.println();
        System.out.println();
    }
    System.out.println("Thank you for using OHMCAL, have a nice day :D");
    System.out.println();
}

}

2 个答案:

答案 0 :(得分:0)

使用==比较Java中的字符串并不能达到您想要的效果。请改用calchoice.equals(...)

答案 1 :(得分:0)

只需使用.equals()代替==