(业余高手学习Java编码器)。我一直在研究这个项目,而且我遇到了一个我无法解决的问题。 这是我需要帮助的地方: (我试图编写一个程序,确定驱动程序是否超速,如果是,那么3张票中哪一张是合适的,以及从帐户中扣除多少钱) 1.如何在if语句中使用reduc变量?当我把它包含在像这样的最后一个if语句中时,我收到一个错误....
//variables
int sbanka = 400;
int speed = 60;
int speedlimit = 60;
int ticket1 = 100;
//logic
//Ticket 1
if(speed > speedlimit + 10) {
System.out.println("You will recieve the level 1 ticket");
boolean reduc = true;
}
else {
System.out.println("Your speed was fine.");
}
//bank account calculation for ticket 1
if(reduc == true && sbanka >-100) {
sbanka -= 100;
System.out.println("we will deduct 100 dollars from your checking account");
这是完成的程序。谢谢你的帮助。
package labs;
public class SpeedingTicket {
public static void main(String[] args) {
//variables
int speed = 50;
int speedlimit = 60;
String text = ("Your account balance is now ");
boolean reduc = false;
//tickets
int t1 = 100;
int t2 = 150;
int t3 = 200;
//Bank account
int sbanka = (400);
//logic
if(speed > speedlimit + 10) {
System.out.println("You are getting a level one ticket");
reduc = true;
}
else {
System.out.println("Your speed was fine.");
reduc = false;
}
if(reduc == true) {
System.out.println(text + (sbanka - t1));
}
if(speed > speedlimit + 20) {
System.out.println("you are getting a level two ticket");
reduc = true;
}
else {
System.out.println("Your speed was fine.");
reduc = false;
}
if(reduc == true) {
System.out.println(text + (sbanka - t2));
}
if(speed > speedlimit + 30) {
System.out.println("This is a serious offence, you are getting a level 3 ticket");
reduc = true;
}
else {
System.out.println("Your speed was fine.");
reduc = false;
}
if(reduc == true) {
System.out.println(text + (sbanka - t3));
}
}
}
答案 0 :(得分:0)
您在{sta} boolean reduc = true;
=>下宣布if(speed > speedlimit + 10){}
。局部变量。所以你不能在if(){}
之外使用它。
好的阅读http://www.geeksforgeeks.org/variable-scope-in-java/
重构如下:
//variables
int sbanka = 400;
int speed = 60;
int speedlimit = 60;
int ticket1 = 100;
boolean reduc = false; // <= Fix your logic here by yourself
//logic
//Ticket 1
if(speed > speedlimit + 10) {
System.out.println("You will recieve the level 1 ticket");
reduc = true;
}
else {
System.out.println("Your speed was fine.");
}
//bank account calculation for ticket 1
if(reduc == true && sbanka >-100) {
sbanka -= 100;
System.out.println("we will deduct 100 dollars from your checking account");