[英]Do…While not looping
I am having trouble with the while
statement in java. 我在使用Java中的while
语句时遇到麻烦。 Here is my code (I am very new to this)... 这是我的代码(对此我很陌生)...
import java.text.DecimalFormat;
import java.util.Scanner;
public class ElecticBillLab6 {
public static void main(String[] args) {
int accountNumber;
int customerName;
int oldMeterReading;
int newMeterReading;
int usage;
double charge = 0;
String name;
String lastName;
String response;
final double baseCharge = 5.00;
int yes = 1;
int no = 2;
boolean YesResponse;
Scanner keyBoard = new Scanner(System.in);
do {
System.out.print("Customer's first Name? ");
name = keyBoard.next();
System.out.print("Customer last name?");
lastName = keyBoard.next();
System.out.print("Enter customer account number ");
accountNumber = keyBoard.nextInt();
System.out.print("Enter old meter reading ");
oldMeterReading = keyBoard.nextInt();
System.out.print("Enter new meter reading ");
newMeterReading = keyBoard.nextInt();
usage = (newMeterReading - oldMeterReading);
if (usage < 301) {
charge = 5.00;
} else if (usage < 1001) {
charge = (5.00 + (.03 * (usage - 300)));
} else if (usage > 1000) {
charge = (35.00 + ((usage - 1000) * .02));
}
DecimalFormat df = new DecimalFormat("$,###.00");
System.out.println("PECO ENERGY");
System.out.println("Customer Account Number " + accountNumber);
System.out.println("Name on Account " + name + lastName);
System.out.println("Last Month Meter Reading: " + oldMeterReading);
System.out.println("This Month Meter Reading: " + newMeterReading);
System.out.println("Current Usage : " + usage);
System.out.println("Your current month charges are "
+ (df.format(charge)));
System.out
.println("Do you want to enter another customer's meter reading?");
System.out.print("Enter 1 for yes or 2 for no.");
response = keyBoard.next();
} while (response == "1");
}
}
The program does it once and does not loop correctly. 该程序执行一次,并且无法正确循环。 What is wrong? 怎么了?
You can't compare strings with ==. 您不能使用==比较字符串。
Use 采用
while(response.equals("1"));
Try: 尝试:
response.equals("1")
==
applied to Strings only returns true
if it's the same object. ==
适用于字符串只返回true
,如果是同一个对象。
This response == "1"
is not how to compare String
s in Java. 此response == "1"
不是如何在Java中比较String
。
You actually want to use response.equals("1")
instead, which will compare the contents of the two String
s which each other and not there memory locations. 实际上,您实际上想使用response.equals("1")
,它将比较两个String
的内容,它们彼此并且不在内存位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.