在while语句中,键入错误的方向后,我得到一个错误,然后继续进行下一个问题。如何格式化以重新引导有效方向?我不知道我是否应该对我这样做,这似乎是正确的方法,但它似乎不起作用
import javax.swing.JOptionPane;
public class taxiService {
public static void main(String [] args) {
//Declare constants
double fareCharge = 5;
double totalMiles = 0;
double finalFareCharged = 0;
double finalxCoord = 0;
double finalyCoord = 0;
double numOfMiles = 0;
double finalCoord = 0;
String error = "Invalid data, please enter valid data!";
String directions = "";
boolean reprompt = true;
//Prompt for direction and miles
while (reprompt) {
totalMiles = numOfMiles + numOfMiles;
directions = JOptionPane.showInputDialog(null, "Please enter a direction: ");
if (directions.equalsIgnoreCase("East")) {
finalxCoord = finalxCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("West")) {
finalxCoord = finalxCoord - numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("North")) {
finalyCoord = finalyCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("South")) {
finalyCoord = finalyCoord - numOfMiles;
reprompt = false;
}
else {
reprompt = true;
JOptionPane.showMessageDialog(null, error);
}
numOfMiles = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter distance in miles: "));
if (numOfMiles > 0) {
JOptionPane.showMessageDialog(null, "miles: " + totalMiles);
}
else
JOptionPane.showMessageDialog(null, error);
}
}
}
答案 0 :(得分:0)
将第二个问题移出循环。我认为这是你最初的想法,但是通过将第二个问题放在循环中而产生了逻辑错误。
import javax.swing.JOptionPane;
public class taxiService {
public static void main(String [] args) {
//Declare constants
double fareCharge = 5;
double totalMiles = 0;
double finalFareCharged = 0;
double finalxCoord = 0;
double finalyCoord = 0;
double numOfMiles = 0;
double finalCoord = 0;
String error = "Invalid data, please enter valid data!";
String directions = "";
boolean reprompt = true;
//Prompt for direction and miles
while (reprompt) {
totalMiles = numOfMiles + numOfMiles;
directions = JOptionPane.showInputDialog(null, "Please enter a direction: ");
if (directions.equalsIgnoreCase("East")) {
finalxCoord = finalxCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("West")) {
finalxCoord = finalxCoord - numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("North")) {
finalyCoord = finalyCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("South")) {
finalyCoord = finalyCoord - numOfMiles;
reprompt = false;
}
else {
reprompt = true;
JOptionPane.showMessageDialog(null, error);
}
}
numOfMiles = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter distance in miles: "));
if (numOfMiles > 0) {
JOptionPane.showMessageDialog(null, "miles: " + totalMiles);
}else {
JOptionPane.showMessageDialog(null, error);
}
}
}
或强>
在显示错误JOptionPane后添加continue;
。这将强制它跳回到循环的开始并再次提示。