在打印全部之前完成数组的输入
我正在尝试对数组进行输入,直到它已满,然后打印整个数组。但我无法让循环运行,直到数组已满,然后打印所有内容。
这是我的代码:
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 语句?
I am trying to do input to an array until it is full and after that print the entire array. But I cannot get the loop to run until the array is full and after that print all.
Here is my code:
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));
}
}
}
How can get the loop to run and then jump to the print statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
循环中的变量
i
永远不可能等于course.length
,因为循环仅运行到i
i
i
i
i
i
i
i
i
。所以i
课程.长度if
块无论如何都是多余的。打印语句应该位于
for
块之后,否则您将在每次迭代中打印数组。the variable
i
in the loop can never be equal tocourse.length
because the loop runs only untili < course.length
. So theif
block is redundant anyway.The printing statement should be AFTER the
for
block, otherwise you'd be printing the array in each iteration.grade [i] = input.nextInt();
之后应该有一个}
。而下面的
if
根本就没有必要。There should be a
}
aftergrade [i] = input.nextInt();
.And the following
if
is not necessary at all.如果在两个赋值语句之后关闭循环,则循环似乎可以完成这项工作。之后的检查没有用,可以删除。
It seems the loop would do the job if it was closed after the two assignment statements. The check afterwards isn't useful and could be removed.
if (i == course.length)
是不必要的,因为当i == length
时,for 循环完成工作,并且 for-loop-body 不会调用,因此删除此行并把它放在闭环"}"
接下来是打印你的数组。将最后一行更改为:
if (i == course.length)
is unnecesery because wheni == length
then for loop finish working and for-loop-body doesn't call so remove this line and put instead of it close loop"}"
Next is printing your array. Change the last line to: