![](/img/trans.png)
[英]string in correct json format but im still getting error while converting
[英]For the Following code,im getting a error InputMismatch exception,even when im providing correct input
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Person {
public enum Sex {
Male, Female
}
String Name;
int Age;
Sex Gender;
String EmailAddress;
public int getAge() {
return Age;
}
static public Person getInstance() {
return new Person();
}
public String getPerson() {
return Name;
}
}
public class TestPerson {
public static void main(String...args) {
List list = new ArrayList();
list.add(Person.getInstance());
list.add(Person.getInstance());
Scanner s = new Scanner(System. in );
for (int i = 0; i < 1; i++) {
System.out.println(list.get(i).Name = s.nextLine());
System.out.println(list.get(i).Age = s.nextInt());
}
s.close();
}
}
聲明列表時,您需要使用泛型。
List<Person> = new ArrayList<Person>();
現在,編譯器知道您打算使用您的Person
對象而不是常規Objects
填充此列表。 如果沒有泛型,則假定列表中將填充沒有Name
和Age
作為變量的對象,因此編譯器會抱怨。
像埃里克爵士所說的那樣使用泛型:
List<Person> = new ArrayList<Person>();
另外:當您使用nextLine();
nextInt();
之后的方法nextInt();
,
nextLine();
在下一次迭代中將以"\\n"
作為輸入,因為nextInt();
僅獲取下一個整數令牌,而不獲取Enter Button ("\\n")
,然后由nextLine();
code
案例中的下iteration
。
無論使用
Integer.parseInt(nextLine());
而不是nextInt();
。 要么
只需使用nextLine();
跳過"\\n"
nextLine();
如下所示:
public static void main(String...args) { List<Person> = new ArrayList<Person>(); list.add(Person.getInstance()); list.add(Person.getInstance()); Scanner s = new Scanner(System. in ); for (int i = 0; i < 1; i++) { System.out.println(list.get(i).Name = s.nextLine()); System.out.println(list.get(i).Age = s.nextInt()); s.nextLine(); //skips the "\\n" } s.close(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.