英文:
Scanner returning unwanted information when trying to use int = input.nextInt in leap year class
问题
import java.util.Scanner;
public class LeapYearCheck{
public static void main(String args[]){
System.out.print("Please enter a leap year:");
Scanner input = new Scanner(System.in);
int year = input.nextInt();
if (year<=1582){
System.out.println("An input of 1582 or less is not valid."); // 1582年或之前的输入无效。
}
else if (year%400==0){
System.out.println(year + " is a leap year."); // 是闰年。
return;
}
else if (year%4==0 && year%100!=0){
System.out.println(year + " is a leap year."); // 是闰年。
return;
}
else{
System.out.println(year + " is not a leap year."); // 不是闰年。
}
}
}
英文:
I'm trying to write a program to check if a year entered by the user is a leap year. I thought what I had below was fine (though I do wish it would return to System.out.print("Please enter a leap year:"); when a year <= 1582 is entered, I'm not sure how to do that), but when I enter a number higher than 1582 I get the following:
run:
Please enter a leap year:1600
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=4][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E] is a leap year.
BUILD SUCCESSFUL (total time: 1 second)
I don't understand why it's printing all of this out, I only want the number that the user entered. I'm new to programming so there is nothing readily obvious about this to me. Thanks, and here's my code:
import java.util.Scanner;
public class LeapYearCheck{
public static void main(String args[]){
System.out.print("Please enter a leap year:");
Scanner input = new Scanner(System.in);
int year = input.nextInt();
if (year<=1582){
System.out.println("An input of 1582 or less is not valid.");
}
else if (year%400==0){
System.out.println(input + " is a leap year.");
return;
}
else if (year%4==0 && year%100!=0){
System.out.println(input + " is a leap year.");
return;
}
else{
System.out.println(input + " is not a leap year.");
}
}
}
答案1
得分: 1
System.out.println(year + "在这里添加任何额外的字符串"); 你的问题在于你试图通过打印 input
来打印扫描器本身。input
不是保存用户输入的变量,你定义了 year
来保存那个信息。
英文:
System.out.println(year+"any extra string here");
your problem is that you are trying to print the scanner itself by printing input
. Input is not the variable that holds the user input, you defined year
to hold that information
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论