Charlie Charlie - 7 months ago 12
Java Question

How do I loop this statement until a user enters 2012?

import java.util.Scanner;
public class whileLoopOlympics
{
public static void main (String[] args)
{
System.out.println ("Which year was the most recent London Olympics?");
Scanner scanner = new Scanner(System.in);
String yearAsString = scanner.nextLine();
int year = Integer.parseInt(yearAsString);


while (year!=2012)
{
System.out.println ("Which year was the most recent London Olympics?");
Scanner next = new Scanner(System.in);
String yearAsString2 = scanner.nextLine();
int year1 = Integer.parseInt(yearAsString2);

}
}
}


I'm trying to loop until the user inputs 2012 however I can't figure out how to do something such as while (year!= 2012 && year1!=2012) I just don't understand how to do this when "year" isn't in the while loop

Answer

You don't need to create new scanner and new variables, you can reuse.

import java.util.Scanner;
public class whileLoopOlympics
{
public static void main (String[] args)
{
    Scanner scanner = new Scanner(System.in);    
    int year = 0;


    while (year!=2012)
    {
        System.out.println ("Which year was the most recent London Olympics?");
        String yearAsString = scanner.nextLine();
        year = Integer.parseInt(yearAsString2);
    }
}
}