2016-09-23 69 views
0

這是一個myProgrammingLab任務,我不確定哪裏出錯了。輸出似乎混淆了變量,我不知道爲什麼。我已經包含了預期的輸出和我的代碼輸出。Java程序正在混合字符串變量

import java.util.Scanner; 

public class WordGame 
{ 
    public static void main(String[] args) 
    { 
     String name; 
     int age; 
     String city; 
     String college; 
     String profession; 
     String animal; 
     String pet; 

     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Enter your name: "); 
     name = keyboard.nextLine();  

     System.out.print("Enter your age: "); 
     age = keyboard.nextDouble(); 

     System.out.print("Enter the name of a city: "); 
     city = keyboard.nextLine(); 

     System.out.print("Enter the name of a college: ");  
     college = keyboard.nextLine(); 

     System.out.print("Enter profession: "); 
     profession = keyboard.nextLine(); 

     System.out.print("Enter a type of animal: "); 
     animal = keyboard.nextLine(); 

     System.out.print("Enter a pet name: "); 
     pet = keyboard.nextLine(); 

     System.out.println("There once was a person named " + name + " who lived in " + city + "." + "At the age of\n" + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to\nwork as a " + profession + ". Then, " + name + " adopted a(n)" + animal + " named " + pet + ". \nThey both lived happily ever after!"); 

    } 
} 

Expected Output: 

Enter·your·name:·Enter·your·age:·Enter·the·name·of·a·city:·Enter·the·name·of·a·college:·Enter·profession:·Enter·a·type·of·animal:·Enter·a·pet·name:·There·once·was·a·person·named·Al·Smith·who·lived·in·Brooklyn.·At·the·age·of↵ 
43,·Al·Smith·went·to·college·at·School·of·Hard·Knocks.·Al·Smith·graduated·and·went·to·↵ 
work·as·a·Politician.·Then,·Al·Smith·adopted·a(n)·Pitbull·named·Toodles↵ 
They·both·lived·happily·ever·after!↵ 
Actual Output: 

Enter·your·name:·Enter·your·age:·Enter·the·name·of·a·city:·Enter·the·name·of·a·college:·Enter·profession:·Enter·a·type·of·animal:·Enter·a·pet·name:·There·once·was·a·person·named·Al·Smith·who·lived·in·.At·the·age·of↵ 
43,·Al·Smith·went·to·college·at·Brooklyn.·Al·Smith·graduated·and·went·to↵ 
work·as·a·School·of·Hard·Knocks.·Then,·Al·Smith·adopted·a(n)Politician·named·Pitbull.·↵ 
They·both·lived·happily·ever·after!↵ 
+0

你'age'是'int',你爲什麼用'年齡= keyboard.nextDouble();'? – DimaSan

+0

對不起,其實是一個錯誤。它原本是age = keyboard.nextInt(); –

回答

1

你的代碼被跳過讀取城市字符串。

年齡使用

age= Integer.parseInt(keyboard.nextLine()); 
+0

完美地工作,謝謝。這給我帶來了比應有的更多的麻煩。 –