2016-02-08 46 views
0

我有一些困難,理解改變用戶輸入的日期和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; 

它不被接受嗎? 我該如何解決這個問題? enter image description here

嘿到目前爲止,我已經遇到一些麻煩的部分代碼:

Calendar cal = Calendar.getInstance(); 
cal.setTime(dayNmonth); 
int day = cal.get(Calendar.DAY_OF_MONTH); 
int month = cal.get(Calendar.MONTH)+ 1; 

在其文摘不會讓我得到了日,月,從「dateOB」與此代碼。 enter image description here

有人可以嘗試並幫助我瞭解問題所在!

+0

您需要幫助的錯誤/例外情況?你通過什麼輸入? – SMA

+0

dateOB是一個字符串值。你不能只把它放在int類型的值中。 MM和mm不同。 MM代表月份,mm代表分鐘。 –

+0

將字符串更改爲int的簡單方法是int date = Integer.parseInt(dateOB.substring(0,2)),int month = Integer.parseInt(dateOB.substring(2,4 ))'''到目前爲止。然後您可以將它與另一個int日期值進行比較。 –

回答

0

將輸入轉換爲Date後,您還可以使用Calendar來獲取信息。

Calendar cal = Calendar.getInstance(); 
cal.setTime(date); 
int day = cal.get(Calendar.DAY_OF_MONTH); 
int month = cal.get(Calendar.MONTH) + 1; 

編輯#1:

得到它將會導致1105輸入你想你要做額外的計算數量,即

int zodiacNumber = month * 100 + day; 

5月11日/ 1984年。反之,你可以使用day * 100 + month如果你喜歡511

或者,您可以通過使用

int zodiac = Integer.valueOf(new SimpleDateFormat("ddMM").format(date))

這是一個更短的解決方案直解析日期到你希望的格式。

編輯#2:當你回答你想要一個循環,以確保日期是在正確的格式輸入的評論一個問題,做這樣的事情:

boolean correctFormat = false; 
do { 
    // ask the user for input 
    // read the input 
    try { 
     // try to format the input 
     correctFormat = true; 
    } catch (ParseException e) { 
     correctFormat = false; 
    } 
} while (!correctFormat); 

你可以肯定的如果拋出異常,日期沒有以正確的方式輸入,因此通過設置助手變量,您可以確保詢問日期,直到它可以轉換,因此是正確的。

編輯#3:如果您使用的是SimpleDateFormat而不是String,則需要使用Date

int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(dateOB)); 

不行!你必須使用

int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date)); 

所以你的程序看起來像這樣:

Date date = new Date(); 
String dateOb = ""; 
boolean correctFormat = false; 
do { 
    (...) 
    date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB); 
    (...) 
} while (...); 
int dayNmonth = Integer.parseInt(new SimpleDateFormat("ddMM").format(date); 
(...) 
cal.setTime(date); 
(...) 

你知道date是真正的日期,而dateOB是很重要的僅僅是用戶輸入的內容 - 這String不能作爲真實日期使用

+0

主啊,謝謝你的回覆,因爲你可以看到我遇到了應用此代碼的問題,或者我不明白它的作用......查看我對Dato建議的評論,我對你的建議做了同樣的評論,然後在最後,我要求程序打印出(day +「」+ month)來查看你建議的這段代碼的產品,輸出是(310 10),所以我不確定這是怎麼來的轉換DoB我提供了哪些是05/11/1984 ....我希望它給我一個數字,如511或0511 ......以便與其他星座比如水瓶座120 -218 – JanusJanus

+0

我做了一個錯誤,因爲'Calendar.MONTH'從0到11,除此之外對我來說工作正常(「5 10」,並將其更改爲'int month = cal.get(Calendar.MONTH)+ 1'後,我收到了「 5 11「)。它可能不會給你想要的數字,但是你仍然可以通過檢查月份和日期是否符合星座來比較星座。 – LordAnomander

+0

完美的是,爲代碼添加+1解決了問題,並感謝您幫助理解問題所在(日曆。月只達到11)所以在做這些之後,我確實得到了511的正確數字,並將其轉換爲zodiacNumber以簡化星座之間的比較,我現在面臨的事情是實現您建議 – JanusJanus

1

我想你可以用「MMdd」格式得到用戶輸入的日期和月份。然後使用Integer.parseInt()獲取一個數字,然後使用if語句來查找十二生肖,因爲它依賴於日期和月份。

例如白羊座。通過做

int userVal=0; 

if (userDate != null) { 
    DateFormat df = new SimpleDateFormat("MMdd"); 
    userVal = Integer.parseInt(df.format(date)); 
} 

現在你可以返回白羊座:日 - 3月4月21日19.所以,你可以從用戶的日期一樣獲得輸入數量

if(userVal >= 321 && userVal <= 419) //Mar 21 == 0321 and April 19 == 0419 
    System.out.println("Your zodiac sign: Aries"); 

只是繼續爲其他跡象。

實施

public static void main(String[] args) throws ParseException { 
    Date date; 
    int mmdd; 
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
    DateFormat mmDDFormat = new SimpleDateFormat("MMdd"); 
    Scanner scanner = new Scanner(System.in); 

    System.out.println("Please enter your date of birth(dd/MM/yyyy):"); 
    String stringDate = scanner.next(); 

    date = dateFormat.parse(stringDate); 

    System.out.println("This is your date of birth: " + dateFormat.format(date)); 

    mmdd = Integer.parseInt(mmDDFormat.format(date)); 

    System.out.println("This is the mmdd value: " + mmdd); 

    //Now getting the Zodiac sign 
    System.out.println("The zodiac sign of your date of birth is: "); 
    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 >= 11 && 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"); 
    } 
} 

Test using netbeans 8.0.1

注:我用的Netbeans 8.0。1

+0

嘿,cdaiga ...我試過你的方式,這是接近Datos和主意的建議,但更短,我明白了,但在我寫這個代碼後,你提供了(int userVal ........... ....)我繼續前進,並打印userVal的數字代碼轉換爲我的出生日期,這應該是0511或511,但我得到一個錯誤:線程「主」的異常java.lang.IllegalArgumentException:無法格式化給定的對象作爲一個日期 \t在java.text.DateFormat.format(DateFormat.java:301) \t在java.text.Format.format(Format.java:157) \t在signs.main(跡象。 java:34) – JanusJanus

+0

我剛剛修改了代碼,我已經測試過,它已經工作。很酷,你理解我的算法。 – cdaiga

+0

正如你所看到的我添加了幾個屏幕截圖,顯示我現在遇到的問題,我宣佈dateOB在循環之外,然後在循環中使用,parseint ....但後來當我試圖得到一天和從轉換後的月份開始,按照您的建議提供的代碼,似乎存在某種衝突! – JanusJanus

1

我建議ü用一個簡單的bean ZodiacSign這樣的:

class ZodiacSign { 
private String name; 
private int  startMonth; 
private int  startDay; 
private int  endMonth; 
private int  ednDay; 

public ZodiacSign(String name, int startMonth, int startDay, int endMonth, int ednDay) { 
    super(); 
    this.name = name; 
    this.startMonth = startMonth; 
    this.startDay = startDay; 
    this.endMonth = endMonth; 
    this.ednDay = ednDay; 
} 

// getter & setter 

}

和遍歷集合,直到你找到一個匹配,就像這樣:

List<ZodiacSign> zodiac = Collections.emptyList(); 
zodiac.add(new ZodiacSign("AQUARIUS", Calendar.JANUARY, 20, Calendar.FEBRUARY, 18)); 
zodiac.add(new ZodiacSign("PISCES", Calendar.FEBRUARY, 19, Calendar.MARCH, 20)); 
// .. 
zodiac.add(new ZodiacSign("CAPRICORN", Calendar.DECEMBER, 22, Calendar.JANUARY, 19)); 
Calendar calendar = Calendar.getInstance(); 
calendar.setTime(date); 
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
int month = calendar.get(Calendar.MONTH); 
for (ZodiacSign sign : zodiac) { 
    if (month >= sign.getStartMonth() && month <= sign.getEndMonth()) { 
     if (dayOfMonth >= sign.getStartDay() && dayOfMonth <= sign.getEdnDay()) { 
      System.out.println("Zodiac Sign: " + sign.getName()); 
     } 
    } 
} 
+0

Stefano非常感謝您的洞察力,您只是讓我瞭解了java中一種新方法,並且我會確保應用您的方式來學習它,但是現在我正試圖實現將簡單將用戶輸入的數據作爲DoB輸入到一個整數中,以便我在switch case方法中將其用於與十二生肖(不同情況)進行比較,同時我想要弄清楚如何進行循環以確保輸入的日期格式爲dd/MM/yyyy – JanusJanus

+0

@Ahmed確保輸入的格式是否正確的一個好方法是使用df.format(date),如果不是並再次提問,請捕獲ParseException! –

1

你可以像下面這樣做

public static void main(String[] args) throws ParseException { 

    Scanner userInput = new Scanner(System.in); 

    System.out.println("Hello you, Lets get to know each other"); 

    String userName; 

    System.out.println("What is your name ?"); 
    userName = userInput.nextLine(); 

    System.out.println(userName + " please enter you DoB (DD/MM/YYY)"); 

    String dateOB = userInput.next(); 
    Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB); 
    System.out.println(dateOB); 

    System.out.println("So your date of birth is " + dateOB); 

    Calendar c = Calendar.getInstance(); 
    c.setTime(date); 
    int day = c.get(Calendar.DAY_OF_YEAR); 


    // IF day is from January 20 - to February 18 this means he or she is aquarius 
    if (day >= 20 && day <= 49) { 
     System.out.println("Aquarius"); 
    } else if (day >= 50 && day <= 79) { 
     //If day if from February 19 to March 20 then pisces 
     System.out.println("Pisces"); 
    } 
    //write all zodiac signs ... 

    userInput.close(); 
} 
+0

Dato,感謝您的完整代碼,它幫助我完成了解如何使用SimpleDateFormat的步驟,但應用了您提供的沒有「if」語句的確切代碼,我希望在代碼的產品下,所以糾正我的MM而不是毫米的錯誤,並添加日曆c = Calendar.getInstance();到int day = ....我去了並添加了System.out.println(day);看看已經轉換的沙發,它給了我一個數字310?對於DoB(05/11/1984)我作爲輸入輸入! – JanusJanus

+0

1984年11月5日是一年中的310天 –

1

好了,終於我能夠克服這個問題,用新的理念感謝充分認識到@LordAnomander他的耐心和詳細說明,@cdaiga見地的替代解決方案和@Dato Mumladze合作。

正確的代碼我迄今達成不生肖比較,我將不得不申請一個開關方法,我相信,因爲我仍然在學習它將面臨其他一些問題,但所有的好東西要學,

import java.util.*; 
import java.text.*; 
import java.lang.*; 

public class signs { 

public static void main(String[] args) throws ParseException { 

    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 
       Date date = new Date(); 
       String dateOB = ""; 
      boolean correctFormat = false;  
       do{ 

       System.out.println(" please enter you DoB (dd/MM/yyyy)"); 
       dateOB = userInput.next(); 

       try{ 
       date = new SimpleDateFormat("dd/MM/yyyy").parse(dateOB); 
        System.out.println("day and month " + dateOB); 
       correctFormat = true; 
       }catch(ParseException e){ 
        correctFormat = false; 
       } 
       }while(!correctFormat); 

//Choosing sign 

      Calendar cal = Calendar.getInstance(); 
      cal.setTime(date); 
      int day = cal.get(Calendar.DAY_OF_MONTH); 
      int month = cal.get(Calendar.MONTH)+ 1; 

// announcing sign 
     //converting the day and month to a number to compare 

       int zodiacNum = day * 100 + month; 
       System.out.println(" zodiac number is " + zodiacNum); 

//closing userInput     
       userInput.close(); 
}  
} 

再次感謝你們,我希望這可以幫助那些有我的基本知識的人,並幫助他們理解一些問題。