【发布时间】:2015-05-28 13:10:32
【问题描述】:
主类:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student std = new Student();
System.out.println("plz , inter id :");
std.setId(input.nextInt());
System.out.println("plz , inter name :");
std.setName(input.next());
System.out.println("plz , inter Age :");
std.setAge(input.nextInt());
System.out.println("plz , inter department :");
std.setDepartment(input.next());
System.out.println("plz , inter GPA :");
std.setGpa(input.nextFloat());
std.printStudentInfo();
}
}
学生班:
public class Student {
private int id;
private String name;
private int age;
private String department;
private float gpa;
public void setId(int Pid) {
this.id = Pid;
}
public int getId() {
return this.id;
}
public void setName(String Pname) {
this.name = Pname;
}
public String getName() {
return this.name;
}
public void setAge(int Page) {
this.age = Page;
}
public int getAge() {
return this.age;
}
public void setDepartment(String Pdepartment) {
this.department = Pdepartment;
}
public String getDepartment() {
return this.department;
}
public void setGpa(float Pgpa) {
this.gpa = Pgpa;
}
public float getGpa() {
return this.gpa;
}
public void printStudentInfo() {
System.out.println("-------------- " + "[" + this.id + "]" + " "
+ this.name.toUpperCase() + " -----------------");
System.out.println("age : " + this.age);
System.out.println("Department : " + this.department);
System.out.println("Gpa : " + this.gpa);
}
}
这是一个简单的应用程序,它从用户那里读取一些数据并将其打印出来,我想在我的两个字符串字段“名称,部门”中从用户那里读取多个单词,但是,当我跨部门名称时像“计算机科学”这样的两个或多个单词,我得到一个错误,我也尝试使用nextline() 而不是next(),类似的结果,我最终又犯了一个错误!
【问题讨论】:
-
nextLine() 应该可以工作,但它总是返回字符串 - 也许您试图将字符串保存在其他变量中?
-
使用 next() ,我得到:java.util.InputMismatchException !
-
它适用于不包含空格的字符串!但是当我尝试使用多字串时,它会抛出一个异常,无论我接下来使用什么方法!
标签: java