2014-12-13 42 views
0

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

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

}

+0

不要使用比较==。使用equals方法进行字符串比较。 – phoenix 2014-12-13 03:38:44

回答

0

使用==不会做你想做的Java中的字符串比较。改为使用calchoice.equals(...)

0

只是使用的.equals()代替==