Java代码输出负数异常问题求助
Hey there, let's break down why your Java parking lot code might be outputting negative numbers. Since your code snippet cuts off at Parking myPar..., I'll walk through the most common culprits that cause this kind of issue with integer-based spot tracking:
Backwards Calculation Logic
This is the most likely culprit. If you're calculating remaining spots using something likeremaining = occupiedSpots - Num_Spotsinstead of the correctremaining = Num_Spots - occupiedSpots, you'll get negative values as soon as more cars are parked than total spots (or even if no cars are parked, since 0 minus a positive number is negative).Unvalidated User Input
Right now, your code accepts any integer forNum_Spots—including negative numbers. If a user accidentally enters-5instead of5, all your subsequent calculations will start from a negative baseline, leading to weird negative outputs across the board.Unbounded Spot Count Modifications
If you later add logic for parking cars or removing them without bounds checks, you can end up withoccupiedSpotsvalues that go below 0 (e.g., trying to remove a car when the lot is empty) or aboveNum_Spots(parking a car when the lot is full). Both scenarios will lead to negative remaining spot counts.Integer Overflow (Less Likely)
While parking lot sizes rarely get this big, if you're doing heavy cumulative calculations with spot counts, you could hit the maximum value of anint(2^31 - 1). When you go beyond that, the integer wraps around to a negative number. This is an edge case, but worth keeping in mind for large-scale systems.
Add Input Validation for Spot Count
Right after readingNum_Spots, add a check to ensure it's a positive number:int Num_Spots = scan.nextInt(); if (Num_Spots <= 0) { System.out.println("Oops, please enter a positive number for available spots."); scan.close(); return; }Lock Down Calculation Logic
Always structure remaining spot calculations to subtract occupied spots from total spots:int occupiedSpots = 0; // Explicitly initialize to 0 for clarity int remainingSpots = Num_Spots - occupiedSpots;And add bounds checks when modifying
occupiedSpots:// When parking a car if (occupiedSpots < Num_Spots) { occupiedSpots++; System.out.println("Car parked successfully!"); } else { System.out.println("Sorry, the lot is full."); } // When removing a car if (occupiedSpots > 0) { occupiedSpots--; System.out.println("Car removed successfully!"); } else { System.out.println("No cars are parked here to remove."); }Explicitly Initialize Variables
Even though Java initializesintvariables to 0 by default, explicitly setting variables likeoccupiedSpots = 0makes your code easier to read and avoids accidental bugs from uninitialized values in more complex classes.
内容的提问来源于stack exchange,提问作者Jallous55

