2012-02-17 35 views
2

我的老師給了我這樣一個問題:如何在這個程序中只使用兩個字符串?

編寫一個程序,執行以下操作:

  • 輸入你的名字:彼得
  • 輸入您的姓氏:Opunga
  • 輸入您的出生年份:1992
  • 您好Peter Opunga,您將在今年年底前20。
  • 獎勵1:適當的評論。 (10%)
  • 獎勵2:在整個程序中只創建2個字符串。 (10%)
  • 加成3:正好使用4個System.out.print。 (10%)

現在我對Java完全陌生。我剛剛被引入到了一點多星期前,這就是我想出了:

import java.io.*; 

public class A1Chuah { 

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

     BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); 

     //Prints instructions for user to enter first name. 
     System.out.println("Enter first name: "); 
     //Obtains user input for first name. 
     String first = in.readLine(); 
     //Prints instructions for user to enter last name. 
     System.out.print ("Enter last name: "); 
     //Obtains user input for last name. 
     String last = in.readLine(); 
     //Prints instructions for user to enter birth year. 
     System.out.print ("Enter your birth year: "); 
     //Obtains user input for birth year. 
     String year = in.readLine(); 
     //Converts String year to int useryr 
     int useryr = Integer.parseInt(year); 
     //Sets int oriyr to value of 2012 
     int oriyr = 2012; 
     //Sets int outyr as oriyr - useryr 
     int outyr = oriyr - useryr; 
     //Prints out information. 
     System.out.println("Hi" + " " + " " + last + "," + " " + "you will be" + " " + outyr + " " + "by the end of this year"); 

我已經成功地完成獎金1和3,但似乎無法找出獎金2。請幫忙! P.S.他說,只要我不想把它作爲我自己的想法來傳遞,我就可以獲得幫助。

+0

看你的意見,你有可能是*不*想出Bonus2那麼好。只是重複陳述所做的評論就是uselss(該陳述更具可讀性並傳達相同的信息)。 「將int oriyr設置爲2012年的值」將確保您無法獲得積分... – Durandal 2012-02-17 11:40:57

回答

4

您可以使用一個字符串來獲取全名和一年中的一個。 你能做到這樣

System.out.println("Enter first name: "); 

    String name = in.readLine(); 

    System.out.print ("Enter last name: "); 

    name+= " " + in.readLine(); 

    System.out.println(name); // should print first and last 
+0

非常感謝您的幫助! – user1215225 2012-02-17 04:12:31

+0

我們歡迎... :) – 2012-02-17 04:14:57

0

您可以重複字符串,所以String last = in.readLine();可以用first = in.readLine();

取代現在,如果你只需要一個字符串在讀,只需要一個字符串的答案...你應該能夠人物從那裏出來如何只用兩個字符串

(提示http://docs.oracle.com/javase/tutorial/java/data/strings.html

0

編輯:對不起,我以爲你是使用java.util.Scanner中的類,所以下面將不會有幫助,除非你覺得切換到該instea d。

以下是你正在使用的假設下寫着:

java.util.Scanner in = new java.util.Scanner(System.in); 
in.nextLine(); 

上一篇:

我認爲你正在尋找in.nextInt();方法,而不是 解析返回字符串的一年誕生。

另外請注意掃描儀有更多的功能,如掃描 模式(RegEx)和標記字符串輸入。

在您可能需要使用像Netbeans一個IDE這 允許您快速通過一類可能的方法瀏覽與 自動完成未來。如果你被允許這樣做。

+0

如果此主題太偏離主題,請隨時要求我將其刪除。 – Hawken 2012-02-17 02:38:33

相關問題