所以,下面是我的代碼:
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
while((res.toUpperCase()).equals("YES")) {
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
for(int i=1; i<50; i ) {
names[i] = n;
}
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
for(int j=0; j<50; j ) {
rolls[j] = r;
}
}
for(int a=0; a<50; a ) {
System.out.println(names[a]);
System.out.println(rolls[a]);
}
}
}
我想要發生的是,該程式應該繼續注冊學生的姓名和卷號。直到陣列已滿或用戶結束它。我該怎么做 ?我走了那么遠
uj5u.com熱心網友回復:
您需要在回圈中有“繼續”問題,并且每次插入名稱時while都不需要回圈。for
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
int index = 0;
while(true) {
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
if(res.toUpperCase().equals("NO") || index == 50)
break;
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
names[index] = n;
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
rolls[index] = r;
index ;
}
for(int i=0; i<50; i ) {
System.out.println(names[i]);
System.out.println(rolls[i]);
}
}
}
uj5u.com熱心網友回復:
使用固定大小的陣列時,一種常見的方法是使用單獨的 int 變數來跟蹤新專案的當前索引位置,以及陣列中使用的總插槽數:
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int size = 50;
String[] names = new String[size];
int[] rolls = new int[size];
int counter = 0;
String res = "";
do {
System.out.print("Do you want to register a student ?(yes/no): ");
res = sc.nextLine().toUpperCase();
if (res.equals("YES")) {
System.out.print("Enter the student's name: ");
names[counter] = sc.nextLine();
System.out.print("Enter their roll number: ");
rolls[counter] = sc.nextInt();
sc.nextLine(); // clear enter out of buffer;
counter ;
}
} while (counter < size && res.equals("YES"));
for(int a=0; a<counter; a ) {
System.out.print(names[a] " : ");
System.out.println(rolls[a]);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456430.html
上一篇:以有效的方式從字串中洗掉特定單詞
下一篇:在訊息中列出陣列
