![](/img/trans.png)
[英]How do I get a string user input and increase value by +1 using Java ArrayList?
[英]How do I add a User Input of type String to an ArrayList in Java?
我正在嘗試建立一個課程注冊系統,並且我的一個課程(課程)圍繞課程屬性(即課程編號,課程名稱,講師,學生)進行。 我正在制作一個ArrayList,以便管理員(用戶類型之一)可以向他/她希望的課程中添加盡可能多的講師-我創建了Scanner和String變量以及所有內容,但是當我編寫.add時命令,Eclipse高亮顯示“ .add”並說“對於掃描儀類型,未定義方法.add()”。 現在,我可以理解了,但是我不知道如何解決它,我已經嘗試了很多想法。
這是方法:
public static String Instructor(){
String courseInstructors;
System.out.println("Please add name(s) of course instructors.");
ArrayList<String> Instructors= new ArrayList<String>();
Scanner courseInst = new Scanner(System.in);
courseInstructors = courseInst.next();
//courseInst.add(courseInstructors);
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
return;
}`
請遵守Java命名約定,變量名稱應使用小寫字母- instructors
而不是Instructors
。
此外,您要添加到您的ArrayList中,所以叫add()
上
instructors.add(courseInstructors1)
您可能還需要考慮選擇更好的變量命名比courseInstructors1
,例如剛剛courseInstructor
,因為你是指在instructor
所有的instructors
。
同樣在for循環中,您正在執行以下操作
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
這可以簡化為
for(String courseInstructors1 : Instructors) {
courseInst.add(courseInstructors);
}
而且,如果您看一下簡化,您會發現遍歷Instructor在這里沒有意義,因為您沒有使用courseInstructors1的內容。
我正在嘗試了解您的循環的用途。
如果您試圖從一個輸入中獲取多個教師姓名,則需要這樣的內容。
//get input
//"John Peggy Adam blah blah"
courseInstructors = courseInst.next();
//split the string by white space
String[] instArr = courseInstructors.split(" ");
//will give array of John, Peggy, Adam, blah, blah
然后執行foreach循環將其添加到列表中。
for(String inst: instArr){
instructors.add(inst);
}
否則,我建議您做這樣的事情,這樣您就不必擔心拆分名稱之類的事情。
courseInstructor = courseInst.nextLine();
while(!courseInstructor.equals("done"){
//add name to list of instructors.
instructors.add(courseInstructor);
//get next name.
courseInstructor = courseInt.nextLin();
//if the user types done, it will break the loop.
//otherwise come back around and add it and get next input.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.