英文:
Showing multiple answers in the output using arrays for java
问题
在我编写显示特定值以下分数的代码时,它只显示了适合条件的整数中的一个,即使有多个满足条件的整数。例如,用户应该输入一个从1到100的整数,并且应显示低于65的分数,但是即使有64和45,它只会显示45。我应该如何显示所有符合条件的值?这是我想出来的代码:
import java.util.Scanner;
import java.util.ArrayList;
public class Tester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> gradeArray = new ArrayList<Integer>();
System.out.print("Enter the number of courses you completed : ");
int course = scan.nextInt();
int highg = 0;
ArrayList<Integer> lowGrades = new ArrayList<Integer>();
for (int i = 1; gradeArray.size() < course; i++) {
System.out.print("Enter the grade received : ");
int grade = scan.nextInt();
if (grade <= 100 && grade >= 0) {
gradeArray.add(grade);
if (grade > 95)
highg = grade;
if (grade < 60)
lowGrades.add(grade);
}
}
System.out.println("Grades qualified for the honors award : " + highg);
System.out.println("Grades that are below passing: " + lowGrades);
}
}
英文:
While I was writing the code for displaying the scores below a certain value, it only showed one of the integer that suits the condition while there were multiple of them. For example the user was to type a integer ranging from 1 to 100 and the scores below 65 should have been displayed, but even though there are 64 and 45, it would only show 45. How am I suppose to show all of the values that suits the condition? Here is my code I've came up
import java.util.Scanner;
import java.util.ArrayList;
public class Tester {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
ArrayList <Integer> gradeArray = new ArrayList<Integer>();
System.out.print("Enter the number of courses you completed : ");
int course = scan.nextInt();
int highg=0;
int lowg=0;
for(int i=1;gradeArray.size()<course;i--){
System.out.print("Enter the grade recieved : ");
int grade = scan.nextInt();
if (grade<=100 && grade >= 0) {
gradeArray.add(grade);
if(grade > 95)
highg = grade;
if (60 > grade)
lowg = grade;
}
}
System.out.println("Grades qualified for the honors award : " + highg);
System.out.println("Grades that are below passing :" + lowg );
}
}
答案1
得分: 0
只返回翻译好的部分:
实际上,您只需编写一个循环以遍历 gradeArray
变量,然后将最后存储在 highg
和 lowg
中的成绩写入。
如果需要的话,您还可以尝试将高值和低值存储在单独的列表中。
英文:
Actually you are writing only the last grades stored in highg
and lowg
. Try writing a loop over the gradeArray
variable.
If needed you can also try to store the high and low values in a separate list
专注分享java语言的经验与见解,让所有开发者获益!
评论