gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:47 24 4
gpt4 key购买 nike

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 (year!= 2012 && year1!=2012) 我只是不明白如何做“年”不在 while 循环中

最佳答案

你不需要创建新的扫描器和新的变量,你可以重复使用。

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

关于java - 在用户输入 2012 之前如何循环此语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36959643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com