Im creating an easy blood transfusion game. I want to get the names and blood type then print them to the console. My code below does this but I cant print it to the console because the variable is inside the loop. How do I fix this?
for ( int i = 0; i < 26; i++)
{
System.out.println("Type your full
name first: ");
String donor = in.next();
System.out.println("Now type your blood type: ");
String bloodType = in.next();
}
If you will first gather all data and then print it out, you should temporarily store them somewhere. A good choice is string array or ArrayList.
ArrayList<String> names = new ArrayList<>(26); // 26 is the initial capacity
ArrayList<String> bloodTypes = new ArrayList(26);
for (int i = 0; i < 26; i++) {
System.out.println("Type your full name first: ");
String donor = in.next();
names.add(donor);
System.out.println("Now type your blood type: ");
String bloodType = in.next();
bloodTypes.add(bloodType);
}
Now you can iterate over the ArrayLists and print out your stored values:
for (int i = 0; i < names.size(); i++) {
System.out.println("Blood type of " + names.get(i) + " is " + bloodTypes.get(i));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.