我有一些困難,理解改變用戶輸入的日期和int與另一個int進行比較的方式。 我試圖讓用戶輸入他的出生日期,然後將它與生肖符號的日期進行比較,如果可能的話。 關於如何將輸入更改爲int,使用pars和SimpleDateFormat的大部分帖子,我無法應用它,如我的代碼中所示,當我嘗試實現「dateOB」時,應該已將其格式化爲INT,在switch語句不承認它是如此...格式化Java中的用戶輸入日期
到目前爲止我的代碼:
import java.util.*;
import java.text.*;
public class signs {
public static void main(String[] args) {
Scanner userInput = new Scanner (System.in);
// Intro message
System.out.println("Hello you, Lets get to know each other");
// User input begin
//name
String userName;
System.out.println("What is your name ?");
userName = userInput.nextLine();
//date of birth
System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
String dateOB = userInput.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
try {
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println(dateOB);
} catch (ParseException e) {
e.printStackTrace();
return;
}
System.out.println("So your date of birth is " + dateOB);
// choosing zodiac sign
//starting the switch statement
int convertedDate = dateOB;
String zodiacSign;
switch (convertedDate){
}
}
}
我將不勝感激,如果有人可以向我解釋如何用簡單的方法實現這一...
所以我得到了你們真正偉大的建議,並且我最終以正確的理解了事物,只是複雜化而已plementing未成年人的建議,讓對碼功能的正確方法,
我走到這一步是:
boolean correctFormat = false;
do{
System.out.println(userName + " please enter you DoB (DD/MM/YYY)");
String dateOB = userInput.next();
try{
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB);
System.out.println(dateOB);
System.out.println("So your date of birth is " + dateOB);
correctFormat = true;
}catch(ParseException e){
correctFormat = false;
}
}while(!correctFormat);
,所以我面臨的問題是,「dateOB現在是因爲它是一個while循環中,在日期格式不正確的情況下,它會檢查日期格式是否正確,因此當我嘗試將日期轉換爲數字時: int dayNmonth = Integer.parseInt(新的SimpleDateFormat(「ddMM」).format(dateOB) );
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
//int month = cal.get(Calendar.MONTH)+ 1;
嘿到目前爲止,我已經遇到一些麻煩的部分代碼:
Calendar cal = Calendar.getInstance();
cal.setTime(dayNmonth);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH)+ 1;
有人可以嘗試並幫助我瞭解問題所在!
您需要幫助的錯誤/例外情況?你通過什麼輸入? – SMA
dateOB是一個字符串值。你不能只把它放在int類型的值中。 MM和mm不同。 MM代表月份,mm代表分鐘。 –
將字符串更改爲int的簡單方法是int date = Integer.parseInt(dateOB.substring(0,2)),int month = Integer.parseInt(dateOB.substring(2,4 ))'''到目前爲止。然後您可以將它與另一個int日期值進行比較。 –