This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 2 years ago.
could someone please explain how the enhanced for loop in the code below would look if it was represented by a standard for loop? ex for(int loop = 0; loop < ____; loop++) etc. I am trying to understand what the enhanced for loop does but want to see how it is represented in a standard for loop.
public static void main(String[] args) {
// get the list of each winning team by year
ArrayList<String> allWinners = readAndPopulateWinnersList();
int startYear = 1956;
for(String teams : allWinners) {
System.out.println(startYear++ + " : " + teams);
}
}
If you want to change your for(String teams: allWinners) to standard loop here it is:
for (int i = 0; i < allWinners.size(); i++) {
System.out.println(startYear++ + " : " + allWinners.get(i));
}
In for each you have simply form without .get(i) etc. but you don't have index either.
So If you want to print allWinners item with its index then standard for loop will be better for you. You can also use Java Streams APi: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
so it will be allWinners.forEach(element -> System.out.println(startYear++ + " : " + element));
Related
I created a list from a text document. I then created a loop to go through it and count every time "strawberry" is in it. But I'm not sure why, it is not working.
I know my list gets created correctly because my print statement at the end returns the correct value. But then it doesn't add up the flavors or the number of times strawberry is present.
import java.util.List;
import java.util.ArrayList;
public class IceCream {
public static void main(String[] args) {
int count, strawberry, average, i;
List<String> flavors = new ArrayList<String>();
TextIO.readFile("src/icecream.dat");
while (TextIO.eof() == false) {
flavors.add(TextIO.getln());
}
count = 0;
strawberry = 0;
for (i = 0; i < flavors.size(); i++); {
count++;
if ( flavors.equals("Strawberry")) {
strawberry++;
}
}
TextIO.putln(flavors.size());
average = strawberry / count * 100;
TextIO.putln("" + count + " ice cream cones were sold. "
+ strawberry + " were strawberry flavored, "
+ "which is a total of " + average + "% of the ice cream cones sold.");
}
}
You are wanting to use ArrayList::get
and compare the Object using equals
if ( flavors.get(i).equals("Strawberry")) {
strawberry++;
}
edit
Also remove the last ; on for (i = 0; i < flavors.size(); i++);
Apart from Scary's answer, you have a semicolon after your for-loop. A semicolon is an empty statement, so you're running an empty statement 374 times, while increasing i to be the size of your list. Afterwards you run the block that was supposed to be the loop's body exactly once, but now i is too big for your list.
Remove the semicolon.
Do not declare your variables god knows where, declare them where you need them. That way you would've gotten a compile error, as i would only be available inside and not outside the loop.
You are comparing the ArrayList object with the String "Strawberry". What you really want is to compare each element with the String. So the statement should be
if(flavors.get(i).equals("Strawberry")) {
strawberry++;
}
I am fairly new to java, so I don't have much experience with the syntax, I have tried some tutorials online and have watched a few videos on while and do while loops in Java from a user input. However, every edit i try breaks my code. The program below takes an answer from the user, an integer from 1 to 20, and has if statements, that carry out the different scenarios. However, I am trying to make it so that it will keep asking the user for an answer, until they input 0. Here is a part of relevant code:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
System.out.println(
"\nPokemon: " + Bulbasaur.getname() +
"\nType: " + Bulbasaur.getthing_about() +
"\nHealth: " + Bulbasaur.gethp() +
"\nAttack: " + Bulbasaur.getattack() +
"\nDefense: " + Bulbasaur.getdefense() +
"\nSpecial attack: " + Bulbasaur.getspattack() +
"\nSpecial defense: " + Bulbasaur.getspdefense()+
"\nSpeed: " + Bulbasaur.getspeed() +
"\nTotal: " + Bulbasaur.gettotal());
}
.
.
.
There are 19 other if statements similar to this (I know this is inefficient code, but i will be making it efficient if it loops).
How would I add a do while/while loop that loops these statements until 0 is entered?
You need to check answer in the loop condition. You can do the check and assignment to answer in one line
int answer;
while ((answer = Integer.parseInt(reader.nextLine())) != 0) {
// code here
}
Your code would be more efficient if you kept the methods like getName() and all 'non-static', so that they could be called from objects of the classes.
If you've understood how to use int[], double[] etc. type of Arrays, what you can do is create an array of objects of the Pokemon like so:
Object[] pokemon = {new Bulbasaur(), new Ivysaur(), new Venusaur()}; // etc. etc.
int answer = Integer.parseInt(reader.nextLine());
answer = answer - 1; // because arrays start at zero, not one
System.out.println("\nPokemon: " + pokemon[answer].getname() +
"\nType: " + pokemon[answer].getthing_about() +
"\nHealth: " + pokemon[answer].gethp() +
"\nAttack: " + pokemon[answer].getattack() +
"\nDefense: " + pokemon[answer].getdefense() +
"\nSpecial attack: " + pokemon[answer].getspattack() +
"\nSpecial defense: " + pokemon[answer].getspdefense()+
"\nSpeed: " + pokemon[answer].getspeed() +
"\nTotal: " + pokemon[answer].gettotal());
Here's a guide to using Objects if you need it.
By making the methods non-static, you can call them from Objects which belong to an array, and all you have to do to add more Pokemon to the array is add , new WhateverPokemon() to it..
Also, if you want to print the choices to the user, you can do so like this:
for(int i = 0; i < pokemon.length; i++)
{
System.out.println(i+1+". "+ pokemon[i].getName());
}
If you want to add this code, then place it immediately after the Object[] pokemon ....
This is a quite intuitive implementation of what you want:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = -1; // Initialize to a trivial value different from 0
while (answer != 0) { // It will not enter here if initialized to 0!
answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
// Code from the if statement
} // End of if
} // End of while
As #Coffeehouse said, you should take a look at what an array is, and try to use it appropriately. It will shorten your code by quite a lot. Step by step, though :)
I am reading from a CSV file that contains data about Hills. I can read the data from the file, and have associated column headers with 6 fields. Currently my output prints like:
### County:Argyll and Bute
[48,Deinn a'Choin,Argyll and Bute,768.2,56.281081,-4.659943, 49,Feinn a'Choin,Argyll and Bute,768.5,56.281043,-4.659924, 50,Zeinn a'Choin,Argyll and Bute,768.7,56.281034,-4.659981]
### County:Stirling
[19,Beinn Each,Stirling,813.0,56.313957,-4.262199, 11,Creag Gharbh,Stirling,637.4,56.46677,-4.221506, 7,Meall Buidhe,Stirling,719.0,56.419004,-4.308645]
### County:Aberdeen
[19,Beinn Each,Aberdeen,813.0,56.313957,-4.262199, 11,Creag Gharbh,Aberdeen,637.4,56.46677,-4.221506, 7,Meall Buidhe,Aberdeen,719.0,56.419004,-4.308645]
But I am trying to get my output like:
### County:Argyll and Bute
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
### County:Stirling
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
### County:Aberdeen
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
So technically what I am trying to achieve is, select 3 values from my SET which are actually inside a map and only print out the name and height.
My code currently is:
for (int i = 0; i < 3; i++) {
System.out.println("### County:" + hillsByCounty.keySet().toArray()[i]);
System.out.println(hillsByCounty.get((hillsByCounty.keySet().toArray())[i]));
}
}
I believe i have to use another for loop, and somehow select only 3 values from the Set and use ".getName" and ".getHeight" in my final print statement
I had an idea of something along the lines
Set<Hill> getHills = hillsByCounty.get((hillsByCounty.keySet().toArray())[i]);
for (int j = 0 ; j < 3 ; j++){
//write to somehow code to pull the hill in pos j in this set
System.out.println(h.getName() + " " + h.getHeight());
}
}
}
But what im not sure about is, how to get these set values. My Map value is a set because my previous method initiates like:
public static Map<String, Set<Hill>> hillsByCounty(List<Hill> hills) {
Sets don't have a get method. You could wrap it in a list e.g.
List<Hill> hills = new ArrayList<>(hillsByCounty.get((hillsByCounty.keySet().toArray())[i]));
or use a for-each loop instead. If you need to only print the first 3 you can add a counter to handle that.
int i = 0;
for (Hill h : hills) {
//Can print here with h however you like
if (++i == 3) {
break;
}
}
Looks like you need to learn about the enhanced for loop, also known as the for-each loop.
Your code should be:
int countyCount = 0;
for (Map.Entry<String, Set<Hill>> entry : hillsByCounty(readHills()).entrySet()) {
System.out.println("### County:" + entry.getKey());
int hillCount = 0;
for (Hill hill : entry.getValue()) {
System.out.println(hill.getName() + " " + hill.getHeight());
if (++hillCount == 3)
break;
}
if (++countyCount == 5)
break;
}
In Java 8, you could also use streaming:
hillsByCounty(readHills()).entrySet()
.stream()
.limit(5)
.forEach(entry -> {
System.out.println("### County:" + entry.getKey());
entry.getValue()
.stream()
.limit(3)
.map(h -> h.getName() + " " + h.getHeight())
.forEach(System.out::println);
});
See:
Javadoc - Map.entrySet()
The Java™ Tutorials - The for Statement
StackOverflow - What is the syntax of enhanced for loop in Java?
StackOverflow - Why is enhanced for loop efficient than normal for loop?
Kindly assist. I am preparing for the Java 7 Programmer 1 exam and came across this question in one of the enthuware Tests.
Question :
Consider the following method:
static int mx(int s)
{
for(int i=0;i<3;i++)
{
s=s+i;
}
return s;
}
And the following code snippet:
` int s=5;
s += s + mx(s) + ++s;
System.out.println(s);`
What will it print ?
End Question
According to the rules on operator precedence , I started by evaluating ++s getting a value of 6 for s, followed by using 6 in the mx method to get a value of 8. Next I added 6+8+6 =20. Then finally carried out the assignment operation as s = 6+ 20 = 26.
The correct answer is 24. I cannot seem to figure out how they come to that answer. Kindly shed some light.
You shouldn't start with ++s, since the evaluation is from left to right.
s += s + mx(s) + ++s;
is the same as
s = 5 + 5 + mx (5) + 6;
which is
s = 5 + 5 + 8 + 6 = 24
The value of s does not change on the ++s because the evaluation of the expression is left to right.
You can check this by modifying your code like this:
public static int mx(int s){
System.out.println(s);
for(int i=0;i<3;i++){
s=s+i;
}
return s;
}
public static void main(String[] args){
int s=5;
s += s+mx(s)+ ++s;
System.out.println(s);
}
The print statement in mx(int s) will print out the value for s, revealing that it is still 5.
Additionaly, if mx(int s) had been passed the value 6 it would return 9 instead of 8.
This question already has an answer here:
Will Java's System.out.print() buffer forever until println()?
(1 answer)
Closed 9 years ago.
Just to understand, what is happening I done the below code:
public class Loopp {
public static void main(String[] args) {
int i=1;
while(true) {
Employee e = new Employee("MyName", i);
i++;
System.out.print(i + " ");
}
}
}
But on console I do not see any output, but when I run this in debug mode, then it prints 2 3 4 ..
I understand that gc is activated again and again to collected the garbage objects, but does that clear console also :|
Edit:
As per the answer , it worked for me, and I learned a new thing today
System.out.println(i + " ");
System.out.flush();
You are using print without flush. Only println has autoflushing semantics.
Add System.out.flush() to your code.