Reputation: 1
I have a problem where my for loop doesn't seem to run in my if statement, the for loop is supposed to print all the values in my list.
import java.util.*;
public class kapitel12 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
List<Float> temperatur = new ArrayList<Float>();
while(true)
{
System.out.println("[L]ägg till temperaturmätning");
System.out.println("[S]kriv ut alla temperaturer och medeltemperatur");
System.out.println("[T]ag bort temperaturmätning");
System.out.println("[A]vsluta");
String val = scan.next();
if (val.equals("L") || val.equals("l"))
{
System.out.println("Lägg till temperatur");
float temp = Float.parseFloat(scan.next());
temperatur.add(temp);
System.out.println(temperatur);
}
else if (val.equals("S") || val.equals("s"))
{
System.out.println("Alla mätningar");
for(int i = 0; i < temperatur.size(); i++)
{
System.out.println("Mätning" + i + ":" + temperatur.get(i));
}
}
}
}
Upvotes: 0
Views: 117
Reputation: 2436
logical conditions in nested if
statement are mutually exclusive, only one of them will be satisfied at time if the condition is met.
Because val
can have one value at time
for example if val="S"
the code block in the first if
will not be executed that results in your v=temperatur
to be empty because it is the first block that adds elements to it.
Upvotes: 0
Reputation: 1389
The loop runs but the size of temperatur is 0, this means the loops end immedently. The temperatur is filled in the if clause, but if you go to if then the next clause else if will not be executed.
You have to fill temperatur before reading the list or define temperatur as class var not as local var.
Upvotes: 1