Java While循环问题(新)
我的程序有问题。Java While循环问题(新),java,if-statement,methods,while-loop,procedural-programming,Java,If Statement,Methods,While Loop,Procedural Programming,我的程序有问题。 我想存储while循环中看到的鸟的数量,然后在程序终止时打印看到最多的鸟。 我对if语句有疑问。 任何帮助都将不胜感激 import java.util.*; class gardenbird { public static void main(String[] main) { askbird(); System.exit(0); }// END MAIN METHOD public static void a
我想存储while循环中看到的鸟的数量,然后在程序终止时打印看到最多的鸟。
我对if语句有疑问。
任何帮助都将不胜感激
import java.util.*;
class gardenbird
{
public static void main(String[] main)
{
askbird();
System.exit(0);
}// END MAIN METHOD
public static void askbird()
{
final int sentinel = -1;
int mostseen = 0;
int howmany = 0;
print("When you want to end the program type in "+sentinel);
while(howmany != sentinel)
{ Scanner scanner = new Scanner(System.in);
print("Which bird have you seen?");
String bird = scanner.nextLine();
howmany = input("How many where in your garden at once?");
if(howmany>mostseen)
{
howmany = mostseen;
}
print("You saw " + howmany+ " " + bird +"\n It was the most common bird in your garden.");
}
}
public static String print(String message)
{
System.out.println(message);
return message;
}
public static int input(String count)
{
Scanner scanner = new Scanner(System.in);
print(count);
String number1=scanner.nextLine();
int number = Integer.parseInt(number1);
return number;
}
}
if语句的内容是向后的,请尝试以下操作:
if(howmany > mostseen)
{
mostseen = howmany;
}
而且
print("You saw " + mostseen + " " + bird +"\n It was the most common bird in your garden.");
也许应该出去玩一会儿?这样,您只会在终止时通知用户,而不是每次用户输入新条目时通知用户。你没有一个真正的设计可以让你打破循环,但这就是你的问题所陈述的……或者,你可以把它放在if语句中,这样只有当条件为真时才会打印出来,就像其他人指出的那样,if块的替换是向后的 创建实用程序方法来执行System.out.println()是过度封装 一次又一次地创建对象会浪费系统资源,并且会降低代码的可读性,但是您的思路是正确的 对比一下
import java.util.Scanner;
public class GardenBird
{
public static void main(String[] main)
{
askbird();
System.exit(0);
}// END MAIN METHOD
public static void askbird()
{
Scanner scanner = new Scanner(System.in);
final int sentinel = -1;
int mostseen = 0;
int howmany = 0;
String mostSeenBird = "";
String currentBird = "";
System.out.println("When you want to end the program type in " + sentinel);
while (howmany != sentinel)
{
System.out.println("Which bird have you seen?");
currentBird = scanner.nextLine();
System.out.println("How many where in your garden at once?");
howmany = Integer.parseInt(scanner.nextLine());
if (howmany > mostseen)
{
mostseen = howmany;
mostSeenBird = currentBird;
}
}
System.out.println("You saw " + howmany + " " + mostSeenBird
+ "\n It was the most common bird in your garden.");
scanner.close();
}
}
howmany=mostseen
应该是mostseen=howmany
。您也可以重新考虑过多使用新的扫描仪实例。