英文:
Trasversing the values in java
问题
import java.util.ArrayList;
import java.util.Scanner;
public class HighestGradeTester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
System.out.println("Enter a grade (between 0 and 100) : ");
int greatest = -1;
int i = 5;
while(scores.size()<5){
int input = scan.nextInt();
if(input <= 100 && input >= 0){
scores.add(input);
if(input >= greatest)
greatest = input;
i--;
if(i != 0)
System.out.println("Enter "+i+" more grades.");
}
}
System.out.println("\nHighest grade: "+greatest);
}
}
英文:
I want to make the statement loop, and I had done it by using the while statement. However, I also want to know wether I can loop the "println" statement by using for loops in the ArrayList instead of the while statement? I want to repeat it fror
import java.util.ArrayList;
import java.util.Scanner;
public class HighestGradeTester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
System.out.println("Enter a grade (between 0 and 100) : ");
int greatest = -1;
int i = 5;
while(scores.size()<5){
int input = scan.nextInt();
if(input <= 100 && input >= 0){
scores.add(input);
if(input >= greatest)
greatest = input;
i--;
if(i != 0)
System.out.println("Enter "+i+" more grades.");
}
}
System.out.println("\nHighest grade: "+greatest);
}
}
答案1
得分: 1
可以的。每个while
循环都可以转换成for
循环。但是你不应该这样做。
for
循环暗示/提示了固定次数的迭代,而这里并非如此。
while
循环更适合,保持原样即可。
英文:
Yes you can. Every while
loop can be transformed into a for
loop. But you should not do that.
for
loops suggest / hint at a fixed number of iterations, which is not the case here.
A while
loop fits better, keep it like it is.
答案2
得分: 0
你可以轻松地将 while 循环转换为 for 循环,同时还可以使用 for 循环循环打印语句。
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
System.out.println("Enter a grade (between 0 and 100) : ");
int greatest = -1;
for(int i = 5; scores.size() < 5; i--){
int input = scan.nextInt();
if(input <= 100 && input >= 0){
scores.add(input);
if(input >= greatest)
greatest = input;
if(i - 1 != 0)
System.out.println("Enter " + (i - 1) + " more grades.");
}
}
System.out.println("\nHighest grade: " + greatest);
}
英文:
You can easily convert while loop into for loop and also you can loop the print statements using for.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
System.out.println("Enter a grade (between 0 and 100) : ");
int greatest = -1;
for(int i=5;scores.size()<5;i--){
int input = scan.nextInt();
if(input <= 100 && input >= 0){
scores.add(input);
if(input >= greatest)
greatest = input;
if(i-1 != 0)
System.out.println("Enter "+(i-1)+" more grades.");
}
}
System.out.println("\nHighest grade: "+greatest);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论