我的程序绘制了一个傻瓜怪物(一个身体和一个头部),并且必须在头部之前绘制该身体。但是当我运行该程序时,它显示“无法添加身体部位!”当我输入2作为输入时(即使已经绘制了主体)。注意:1作为输入绘制主体,2作为绘制头部。
我已经确定了问题,但不确定如何解决。问题是磁头在进入“ if(rollValue == 2)...”之前被重置为0。我的程序可以绘制身体,但是在绘制完身体之后,我的“ body”变量似乎设置为0。这就是为什么我的程序没有绘制头部。关于如何修复它的任何想法,以便我的程序在绘制主体后不会将“主体”重置为0?
import java.util.Scanner;
public class Cootie
{
public static void main(String[] args)
{
boolean done = false;
while (!done)
{
Scanner scanner = new Scanner(System.in);
System.out.println("BODY PARTS:");
System.out.println("1 = body");
System.out.println("2 = head");
System.out.println("3 = one leg");
System.out.println("4 = one antenna");
System.out.println("5 = one eye");
System.out.println("6 = tail");
System.out.println("What number did you roll?: ");
int rollValue = scanner.nextInt();
int body = 0;
int head = 0;
if (rollValue == 1)
{
if (body == 0)
{
body = 1;
}
else
{
System.out.println("Can't add body part!");
System.out.println(" ");;
}
}
else if (rollValue == 2)
{
if (body == 1 && head == 0)
{
head = 1;
}
else
{
System.out.println("Can't add body part!");
}
}
else
{
System.out.println("Enter a valid input!");
}
if (body == 1)
{
System.out.println("------------------------------");
System.out.println("You got the body!");
System.out.println(" ");
System.out.println(" ");
System.out.println(" [ ]");
System.out.println(" ");
System.out.println(" [ ]");
System.out.println(" ");
System.out.println(" [ ]");
System.out.println(" ");
}
if (head == 1)
{
System.out.println("You got the head!");
System.out.println(" ");
System.out.println(" ( )");
}
if (body == 1 && head == 1)
{
System.out.println("Congratulations you have completed your cootie!");
done = true;
}
}
}
}
最佳答案
您已经在body
循环内声明了head
(和while
)变量,因此它将在每个循环中运行:
int body = 0;
int head = 0;
因此,在每个循环中,这些变量都将重置为
0
。要保留不同迭代的值,请在while
循环之前声明并初始化它们,以便仅将它们初始化为0
一次。 (您也可以在循环开始之前声明和初始化Scanner
。)int body = 0;
int head = 0;
Scanner scanner = new Scanner(System.in);
while (!done)
{
// Other code still the same
关于java - 为什么将“body”重置为零?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26186711/