3 回答

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以簡(jiǎn)化程序的邏輯并編寫如下內(nèi)容,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
您應(yīng)該使用 adynamic list因?yàn)槟荒茉?Java 中調(diào)整數(shù)組的大小。第二點(diǎn)當(dāng)用戶給出“完成”時(shí),你不應(yīng)該把它放在列表中,所以在插入之前檢查它。

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
您聲明了大小為 0 的 String 數(shù)組。這就是您不能向其中添加元素的原因。
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
試試這個(gè)代碼,或者你可以選擇任何其他數(shù)據(jù)結(jié)構(gòu)。
添加回答
舉報(bào)