【发布时间】:2018-04-08 19:52:37
【问题描述】:
我对这段代码的输出有疑问:
import java.util.Scanner;
public class Parking
{
public static void main(String[]args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter the name of the parking lot:");
String Name=scan.nextLine();
System.out.println("Enter the address of the parking lot:");
String Address=scan.nextLine();
System.out.println("Enter the number of spots available for this parking lot:");
int Num_Spots=scan.nextInt();
System.out.println();
Parking myParking= new Parking(Name,Address,Num_Spots);
System.out.println("This is the information you provided about this parking lot:\n"+ myParking);
System.out.println();
String toQuit;
boolean quit=false;
while(!quit)
{
System.out.println("How many cars are exiting?");
int CarsExiting=scan.nextInt();
System.out.println("How many cars are entering?");
int CarsEntering=scan.nextInt();
while(CarsEntering>(Num_Spots+CarsExiting))
{
System.out.println("I'm sorry, the number of cars entering must be less than number of spots available.");
System.out.println("Please inform the remaining customers that this lot is full.");
System.out.println("How many cars are entering now?");
CarsEntering=scan.nextInt();
}
System.out.println("The number of spots available now is: "+CarFlow(CarsEntering,CarsExiting));
System.out.println("Press 'Q' to quit and any key to continue");
toQuit=scan.next();
if(toQuit.equalsIgnoreCase("Q"))
{
quit=true;
}
}
}//end main
private String _Name;
private String _Address;
private static int _Num_Spots;
// constructor for the parking class
public Parking(String Name,String Address, int Num_Spots)
{
_Name = Name;
_Address = Address;
_Num_Spots = Num_Spots;
}
//getters
public String getName() {return _Name;}
public String getAddress() {return _Address;}
public int getNumSpots() {return _Num_Spots;}
//setters
public void setName(String Name) {_Name=Name;}
public void setAddress(String Address) {_Address=Address;}
public void setNumSpots(int Num_Spots) {_Num_Spots=Num_Spots;}
//CarsFlow method()
public static int CarFlow(int CarEn,int CarEx)
{
_Num_Spots=_Num_Spots+CarEx;
_Num_Spots= _Num_Spots-CarEn;
System.out.println("The number of cars exiting is "+CarEx);
System.out.println("The number of cars entering is "+CarEn);
return _Num_Spots;
}
public String toString()
{
String Output="The name of the parking lot is: "+_Name+
"\nThe address of the parking lot is: "+_Address+
"\nThe number of spots available in this parking lot is: "+_Num_Spots;
return Output;
}
}//end Parking class
输出一开始工作正常,然后在某些时候当我输入的汽车数量超过可用点数时,我得到这个输出:
退出的汽车数量为0 进入的汽车数量是10 现在可用名额为:0 按“Q”退出,按任意键继续 r 有多少辆车正在退出? 0 有多少汽车进入? 3 离开的汽车数量为0 进入的汽车数量为3 现在可用的点数是:-3
当程序应该通过 while 循环并打印一条消息说进入的汽车数量大于可用点的数量时,我得到一个负数,因为 3 大于 0。
【问题讨论】:
-
你的问题是?
-
然后用 inut 写一个@Test,然后对你的代码进行错误处理。然后,您将 1. 找到错误 2. 修复它并 3. 进行测试以确保它不会再次出现!