我有麻煩轉換字符串(birthyear)成int(年齡)。我希望有人輸入他們的出生年份,並讓程序做一個簡單的減法計算來計算他們的年齡。我是編程新手,所以我一直在尋找,大多數地方告訴我同樣的事情。二元運算符的不良操作數類型「 - 」第一種類型:int;第二種類型:java.lang.String
Integer.parseInt(birthyear);
不過,話說這樣做,當我嘗試做數學題......
int age = year-birthyear;
我得到錯誤的稱號。
public class WordGameScanner
{
public static void main(String[] argus)
{
String name;
String home;
String birthyear;
String course;
String reason;
String feedback;
int year = 2013;
Scanner input = new Scanner(System.in);
System.out.print("What is your name: ");
name = input.nextLine();
System.out.print("Where are you from: ");
home = input.nextLine();
System.out.print("What year were you born: ");
birthyear = input.nextLine();
Integer.parseInt(birthyear);
System.out.print("What are you studying: ");
course = input.nextLine();
System.out.print("Why are you studying " + course + ": ");
reason = input.nextLine();
System.out.print("How is " + course + " coming along so far: ");
feedback = input.nextLine();
int age = year-birthyear;
System.out.println("There once was a person named " + name +
" who came all the way from " + home +
" to study for the " + course +
" degree at --------------.\n\n" + name +
" was born in " + birthyear + " and so will turn " + age +
" this year.");
System.out.println(name + " decided to study the unit ------------, because \"" +
reason + "\". So far, ----------- is turning out to be " +
feedback + ".");
}
}
對不起,如果這是在錯誤的地方,這只是我的第二篇文章在這裏。我只是點擊「問一個問題」,然後按照指示>。 <
你只是丟棄()''用整數#parseInt函數的返回值。不要這樣做。 – 2013-03-04 23:13:09
快速問題:您是如何將代碼發佈到所有縮進問題的?當我嘗試使用「代碼塊」時,它完全沒有縮進地發佈它。 – Mav 2013-03-04 23:16:47
只需按下「Tab」,我就可以使用[Chrome擴展讓我縮進代碼塊](https://chrome.google.com/webstore/detail/textarea-code-formatter/dgkbnngeehclnibbdblaimapibmmcdal),但您應該沒有問題通過粘貼代碼獲得相同的結果,在編輯器中突出顯示它,然後按下「代碼」按鈕。 – 2013-03-04 23:42:24