在while循环中,我尝试将购买设置为用作输入存储设备的选项,并从可购买选项中进行选择。
我想知道是否可能,如果是,如何,同时接受布尔值或整数,取决于用户是想增加pageAmount还是购买升级。
import java.util.Scanner;
public class BookieClickerV1
{
public static void main(String [] args)
{
double pageAmount = 0;
int penNumber = 0;
int scribeNumber = 0;
int printingNumber = 0;
int printerNumber = 0;
int conwayNumber = 0;
int mageNumber = 0;
boolean gameStarted = true;
boolean click = false;
int purchase = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to Bookie Clicker V1.0.");
System.out.println("As this is the first version of the game, it can be rather buggy");
System.out.println("When you are ready to begin, type 'True' to represent a click.");
System.out.println("Use the reference handed to you to know what you're purchasing.");
while (gameStarted = true)
{
click = reader.nextBoolean();
if (purchase == 1)
{
pageAmount -= Math.pow(15, (1.2 * (penNumber + 1)));
penNumber += 1;
purchase = 0;
}
if (purchase == 2)
{
pageAmount -= Math.pow(100, (1.2 * (scribeNumber + 1)));
scribeNumber += 1;
purchase = 0;
}
if (click == true)
{
if (penNumber > 0)
{
pageAmount++;
}
pageAmount++;
click = false;
System.out.println("Your total number of pages written is " + pageAmount);
}
}
}
}
答案 0 :(得分:2)
您可以接受整行,然后查看它是否为整数。像这样:
String line = reader.nextLine();
try {
int purchase = Integer.parseInt(line);
// ...
} catch (NumberFormatException e) {
// Just use .equals() if you want it to be case-sensitive.
if (line.equalsIgnoreCase("True" /* or "Click", etc. */)) {
// ...
}
}
另请注意,您的行中有错误
while (gameStarted = true)
使while循环无限(因为=
将gameStarted
变量设置为true
,导致循环永远不会结束)。它应该是
while (gameStarted == true)
或只是
while (gameStarted)
答案 1 :(得分:0)
这可能不是最有效的解决方案,当然也不是最复杂的解决方案,因为我在高中时只学了两年Java,所以没有花哨的方法或特殊的东西。
你可以使用这样的代码块:
String a = scanner.next();//store input, makes it easier to manipulate
if(a.startsWith("T") || a.startsWith("F"))//this assumes the user enters true/false as an input
{
//execute correct code, you could set a boolean true, execute a method
//or whatever else you wanted to do
}
else
{
int upgradeInt = Integer.parseInt(a);//you need this to get the
//input converted into an int. This is an edit, I forgot this step.
//executes correct code and can use String a to pass an upgrade or
//however you need your code to run
}
我这样做是因为我不喜欢,但我不相信这是解决问题的最有效或最正确的方法。而且,正如Doorknob指出的那样,while - loop
的条件不应该只有一个=
,而应该有一个==
,因为这是比较原始数据(如布尔值)的正确方法。在您拥有的情况下,您将布尔值设置为某个值,在这种情况下,这将使您进入无限循环。