我正在尝试对数组进行输入,直到它已满并在此之后打印整个数组。但是我无法让循环运行,直到数组已满并且打印完毕后才会运行。
这是我的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++){
course[i] = input.next();
grade [i] = input.nextInt();
if (i == course.length)
break;
//System.out.println("\nHow do you want to order course and grade?");
//System.out.print(" 1 - Ascending?\n"
// + " 2 - Decending?\n");
//System.out.println("Name and grade is " + course[i] + " " + grade[i]);
System.out.println(Arrays.toString(course)+(grade));
}
}
}
如何让循环运行然后跳转到print语句?
答案 0 :(得分:0)
循环中的变量i
永远不能等于course.length
,因为循环只运行到i < course.length
。所以if
块无论如何都是多余的。
打印语句应该在for
块之后,否则你将在每次迭代中打印数组。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade [i] = input.nextInt();
}
System.out.println(Arrays.toString(course)+(grade));
}
答案 1 :(得分:0)
}
之后应该有grade [i] = input.nextInt();
并且根本不需要以下if
。
答案 2 :(得分:0)
如果在两个赋值语句之后关闭循环,那么循环似乎就能完成。之后的检查无效,可以删除。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[2]; // creating array
int[] grade = new int[2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade[i] = input.nextInt();
}
System.out.println(Arrays.toString(course) + (grade));
}
答案 3 :(得分:0)
if (i == course.length)
是不必要的,因为当i == length
然后for循环完成工作而for-loop-body没有调用所以删除这一行而不是把它关闭循环"}"
接下来是打印你的数组。将最后一行更改为:
System.out.println(Arrays.toString(course) + Arrays.toString((grade)));