如何在用户输入2012之前循环此语句?

时间:2016-04-30 20:04:06

标签: java

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);

}
}
}

我试图循环直到用户输入2012但是我无法弄清楚如何做一些事情,例如while(年!= 2012&& year1!= 2012)我只是不要&# 39,了解如何在"年"不在while循环中

4 个答案:

答案 0 :(得分:4)

您无需创建新的扫描仪和新变量,您可以重复使用。

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(yearAsString);
    }
}
}

答案 1 :(得分:0)

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

    }
}

试试这个

答案 2 :(得分:0)

总结一下我在评论中看到的一些想法:

你应该尽量不要重复你的代码。您不必使用这么多变量和扫描仪(您甚至可以声明一些您从不使用)。

// Do not declare a new scanner for any line you read
Scanner scan = new Scanner(System.in);
// If you're as maniac as I am, you can use only ONE string as well (or even no String...)
String user_input;
int year = 0;

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

答案 3 :(得分:-1)

我将其更改为do/while

 public static void main (String[] args)
    {
        int year = -1;

        do{
            System.out.println ("Which year was the most recent London Olympics?");
            Scanner scanner = new Scanner(System.in);
            String yearAsString = scanner.nextLine();

            try{
                year = Integer.parseInt(yearAsString);

            }catch (NumberFormatException nfe){
                System.out.println ("Invalid year; numbers only please");
            }
        }while (year != 2012 );
        System.out.println ("Correct! Thanks");
    }