Java.....can someone please help me change that for loop to an enhanced for loop
ID: 3684703 • Letter: J
Question
Java.....can someone please help me change that for loop to an enhanced for loop. Everything works, I just need the for loop to be an enhanced loop. THanks
import java.util.ArrayList;
public class P9
{
public static void main(String[] args)
{
double sum = 0;
int count = 0;
ArrayList<Score> list = new ArrayList<Score>();
Score<String, Double> s1 = new Score<String, Double>("Donatello", 3.0);
Score<String, String> s2 = new Score<String, String>("April", "Five");
Score<String, Double> s3 = new Score<String, Double>("Raphael", 3.5);
Score<String, String> s4 = new Score<String, String>("Shredder", "One");
Score<String, String> s5 = new Score<String, String>("Splinter", "Seven");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
for(int i=0; i < list.size(); i++)
{
Score s = list.get(i);
String str = s.toString();
System.out.println(str);
if(s.getScore() instanceof Double)
{
sum = sum + Double.parseDouble(s.getScore().toString());
count++;
}
}
System.out.println("Average of numerical scores: " + (sum / count));
}
}
-------------------------------------------------------------------
public class Score<String, T>
{
private String name;
private T score = null;
public String getName()
{
return name;
}
public void setName(String name, T score)
{
this.name = name;
}
public T getScore()
{
return score;
}
public void setScore(T score)
{
this.score = score;
}
public Score(String name, T score)
{
this.name = name;
this.score = score;
}
@Override
public java.lang.String toString()
{
return "Name: " + name + " Score: " + score;
}
}
Explanation / Answer
P9.java
import java.util.ArrayList;
public class P9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Score> list = new ArrayList<Score>();
Score<String, Double> s1 = new Score<String, Double>("Donatello", 3.0);
Score<String, String> s2 = new Score<String, String>("April", "Five");
Score<String, Double> s3 = new Score<String, Double>("Raphael", 3.5);
Score<String, String> s4 = new Score<String, String>("Shredder", "One");
Score<String, String> s5 = new Score<String, String>("Splinter", "Seven");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
double sum = 0;
int count = 0;
//for(int i=0; i<list.size(); i++){
for(Score s : list){
String str = s.toString();
System.out.println(str);
if(s.getScore() instanceof Double){
sum = sum + Double.parseDouble(s.getScore().toString());
count++;
}
}
System.out.println("Average of numerical scores: "+(sum/count));
}
}
Output:
Name : Donatello Score : 3.0
Name : April Score : Five
Name : Raphael Score : 3.5
Name : Shredder Score : One
Name : Splinter Score : Seven
Average of numerical scores: 3.25
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.