2017-11-11 111 views
-7

我有一个“线程异常”错误。我创建了一个公共类student并给它三个类:学生的姓名,学生的ID和学生的GPA。当我运行代码并为student1输入信息时,这很好。但是,当我输入student2时,代码会跳过student2的名称,并为我提供学生ID和GPA。我该如何补救?java中的异常线程

output exception

下面是代码:

import java.util.Scanner; 
class Student { 

    public String name; 
    public int id; 
    public float gpa; 
} 
public class learning { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     Student s1 = new Student(); 
     System.out.print("Enter your name: "); 
     s1.name = input.nextLine(); 
     System.out.print("Enter your id: "); 
     s1.id = input.nextInt(); 
     System.out.print("Enter your gpa: "); 
     s1.gpa = input.nextFloat(); 


     Student s2 = new Student(); 
     System.out.print("Enter your name: "); 
     s2.name = input.nextLine(); 
     System.out.print("Enter your id: "); 
     s2.id = input.nextInt(); 
     System.out.print("Enter your gpa: "); 
     s2.gpa = input.nextFloat(); 


     Student s3 = new Student(); 
     System.out.print("Enter your name: "); 
     s3.name = input.nextLine(); 
     System.out.print("Enter your id: "); 
     s3.id = input.nextInt(); 
     System.out.print("Enter your gpa: "); 
     s3.gpa = input.nextFloat(); 

     System.out.println("your name: " + s1.name + "\n" 
       + "your id: " + s1.id + "\n" 
       + "your GPA: " + s1.gpa); 

    } 

} 
+1

欢迎来到Stackoverflow,请阅读[如何提问](https://stackoverflow.com/help/how-to-ask)。请特别注意[如何创建MCVE](https://stackoverflow.com/help/mcve)。您将付出更多努力发布一个好问题:一个容易阅读,理解和[主题](https://stackoverflow.com/help/on-topic) - 的机会更高会吸引相关人员,你会得到更快的帮助。祝你好运! – alfasin

+0

显示您的代码,以便我们弄清楚发生了什么 – VHS

+0

请在此处查看 https://pastebin.com/grCEuM9w –

回答

1

您的扫描仪越来越搞砸了,如果你都使用nextLinenext/nextInt/nextDoublethis了解更多信息。

我改变了你的主要方法,现在它就像你想要的那样工作。

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    Student s1 = new Student(); 
    System.out.print("Enter your name: "); 
    s1.name = input.nextLine(); 
    System.out.print("Enter your id: "); 
    s1.id = Integer.parseInt(input.nextLine()); 
    System.out.print("Enter your gpa: "); 
    s1.gpa = Float.parseFloat(input.nextLine()); 

    Student s2 = new Student(); 
    System.out.print("Enter your name: "); 
    s2.name = input.nextLine(); 
    System.out.print("Enter your id: "); 
    s2.id = Integer.parseInt(input.nextLine()); 
    System.out.print("Enter your gpa: "); 
    s2.gpa = Float.parseFloat(input.nextLine()); 

    Student s3 = new Student(); 
    System.out.print("Enter your name: "); 
    s3.name = input.nextLine(); 
    System.out.print("Enter your id: "); 
    s3.id = Integer.parseInt(input.nextLine()); 
    System.out.print("Enter your gpa: "); 
    s3.gpa = Float.parseFloat(input.nextLine()); 

    System.out.println("your name: " + s1.name + "\n" + "your id: " + s1.id + "\n" + "your GPA: " + s1.gpa); 

} 
相关问题