2016-09-23 42 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

完美地工作,谢谢。这给我带来了比应有的更多的麻烦。 –