이 프로그램에서 출력을 올바르게 가져 오는 데 문제가 있습니다. 유효한 날짜 입력 (즉, 2014 년 3 월 22 일)과 유효하지 않은 입력 (2014 년 3 월 57 일)을 해독하는 데 도움이되는 매개 변수가 포함되었습니다. 이것들은 if 문 내 for 루프 내에 있습니다. 그러나 프로그램을 실행할 때 else 문을 계속 출력하고 왜 그 이유가 확실하지 않습니다. String과 int에서 행 유형을 전환했습니다. 내 실수가 보이니? 위해 같이 IndexOf를 사용하는 덕분에Java : 날짜 변환 출력 오류
import java.util.Scanner;
import javax.swing.*;
public class ConvertDate
{
public static void main(String[] args)
{
String enteredDate, month, day, year;
final String[] monthID = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
final int[] monthIDArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
final String[] monthValidSingleInputs = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12"};
final String[] monthValidDosInputs = {"01", "02", "03", "04", "05", "06", "07", "08", "09",
"10", "11", "12"};
final String[] monthsDays = {"31", "28", "31", "30", "31", "30", "31", "31", "30", "31",
"30", "31"};
final int[] intDaysArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
final int JANUARY = 1;
final int DECEMBER = 12;
int selectedDate;
int x;
enteredDate = JOptionPane.showInputDialog(null, "Enter a date in the format MM/DD/YYYY");
주요 문제는 당신의 for loop
로했다/
int slashIndex = enteredDate.indexOf("/");
//Finding the month
month = enteredDate.substring(0, slashIndex);
int intMonth = Integer.parseInt(month);
enteredDate = enteredDate.substring(slashIndex + 1);
enteredDate = enteredDate.trim();
//Finding the day
slashIndex = enteredDate.indexOf("/");
day = enteredDate.substring(0, slashIndex);
int intDay = Integer.parseInt(day);
enteredDate = enteredDate.trim();
enteredDate = enteredDate.substring(slashIndex + 1);
//Finding the year
year = enteredDate.substring(0, 4);
int intYear = Integer.parseInt(year);
enteredDate = enteredDate.trim();
의 출력 문
for(x = 0; x < monthID.length; ++x)
{
if(((month == monthValidSingleInputs[x]) || (month == monthValidDosInputs[x])) && (intDay <=
intDaysArray[x]) && ((intMonth >= JANUARY) && (intMonth <= DECEMBER)))
JOptionPane.showMessageDialog(null, "Date is: " + monthID[x]
+ " " + intDay + ", " + year);
else
JOptionPane.showMessageDialog(null, "Please re-run program, entries not valid.");
break;
}}}
문자열 값을 비교하려면 == 대신 String.equals를 사용하십시오. –
오류는 첫 번째 반복 후에 루프를 종료하는'break' 문과 함께'=='와 함께 있습니다. 답변으로 수정 된 코드를 게시했습니다. –