Java程序作业问题:输入字符串分割与星座计算错误排查
Hey there! Let's break down what's going wrong with your code and fix it up so it works exactly as you expect.
The Core Issue: Wrong mmdd Calculation
The biggest mistake here is how you're computing the mmdd value. Right now you're using:
mmdd = a + b;
For input 01/06, this gives you 1 + 6 = 7—way off from the expected 106. Instead of adding the month and date, you need to concatenate them into a single numeric value. The correct formula is:
mmdd = a * 100 + b;
This shifts the month value two digits left (multiplying by 100) and appends the date, giving you the combined mmdd number you need.
Smaller Fixes & Improvements
- Avoid redundant
split()calls: You're splitting the input string twice, which is unnecessary. Store the split result in an array first to make your code cleaner and more efficient. - Fix Capricorn's date range: Your current condition for Capricorn includes
mmdd >= 11, but sincemmddis calculated asmonth*100 + date, the smallest possible January value is101(1/01). That condition should bemmdd >= 101instead. - Close the scanner: It's good practice to close the
Scannerobject when you're done with it to free up resources.
Corrected Full Code
import java.util.Scanner; public class ZodiacSign { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int mmdd; int month; int day; System.out.print("Please enter your date of birth(MM/dd): "); String stringDate = scan.next(); // Split once and reuse the result String[] dateParts = stringDate.split("/"); month = Integer.parseInt(dateParts[0]); day = Integer.parseInt(dateParts[1]); // Calculate mmdd correctly mmdd = month * 100 + day; System.out.println("This is the mmdd value: " + mmdd); System.out.print("Result: "); if (mmdd >= 321 && mmdd <= 419) { System.out.println("ARIES"); } else if (mmdd >= 420 && mmdd <= 520) { System.out.println("TAURUS"); } else if (mmdd >= 521 && mmdd <= 620) { System.out.println("GEMINI"); } else if (mmdd >= 621 && mmdd <= 722) { System.out.println("CANCER"); } else if (mmdd >= 723 && mmdd <= 822) { System.out.println("LEO"); } else if (mmdd >= 823 && mmdd <= 922) { System.out.println("VIRGO"); } else if (mmdd >= 923 && mmdd <= 1022) { System.out.println("LIBRA"); } else if (mmdd >= 1023 && mmdd <= 1121) { System.out.println("SCORPIO"); } else if (mmdd >= 1122 && mmdd <= 1221) { System.out.println("SAGITTARIUS"); } else if ((mmdd >= 1222 && mmdd <= 1231) || (mmdd >= 101 && mmdd <= 119)) { System.out.println("CAPRICORN"); } else if (mmdd >= 120 && mmdd <= 218) { System.out.println("AQUARIUS"); } else if (mmdd >= 219 && mmdd <= 320) { System.out.println("PISCES"); } scan.close(); } }
Test It Out
If you input 01/06 now, the code will calculate mmdd = 1 * 100 + 6 = 106, which falls right into the Capricorn range (101-119). You'll get the expected output: CAPRICORN.
内容的提问来源于stack exchange,提问作者daboogymenz06

