【发布时间】:2026-01-01 01:15:02
【问题描述】:
这是我的代码:
int yaya = 5;
int x = 10;
do {
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.out.println("Vote Ballot");
System.out.println("Below are the 2 Canditates you can choose to vote from");
System.out.println("Mar Roxas --- Code: 11");
System.out.println("Duterte ---- Code: 12");
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.out.println("Who do you vote? Enter numbers only!");
int choice = input.nextInt();
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
if (choice == 11)
{
System.out.println("You have voted Mar Roxas and not Duterte");
}
else if ( choice == 12 )
{
System.out.println("You have voted Duterte and not Mar Roxas");
}
else
{
System.out.println("You have entered an invalid number");
}
String confirm = "confirm";
String deny = "deny";
int conf = 1;
int den = 2;
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.out.println("Do you want to let another voter vote? Or would you like to end the program at hand?");
int ans = input.nextInt();
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
if ( ans==1 )
{
System.out.println("The program would now repeat");
}
else if ( ans==2 )
{
if ( choice ==11 )
{
int RoxasC = 0;
int DuterteC = 0;
RoxasC+=1;
System.out.println("Mar roxas recieved " +RoxasC+ " number of vote/s and Duterte Recieved " +DuterteC+
" number of votes");
}
else if ( choice ==12)
{
int RoxasC = 0;
int DuterteC = 0;
DuterteC+=1;
System.out.println("Duterte recieved " +DuterteC+ " number of vote/s Roxas received " +RoxasC+
" number of votes");
}
System.out.println("Program will end as per request");
break;
}
else
{
System.out.println("You entered an invalid keyword program would still repeat");
}
System.out.println("\n");
} while( yaya==5 ); //Program Runs Infinitely
这是我的问题:
假设我运行了一次程序并选择投票给 Mar Roxas。我输入数字 11。如果我选择停止该程序,它会计算并显示 Mar Roxas 获得一票,而另一个人获得 0。到目前为止,一切都很好。当我决定选择继续循环时(这将重新运行程序),就会出现问题。
当我决定投票给另一位政治家并决定结束该计划时,我对 Mar Roxas 的初始投票变为 0,而 Duterte 得到 1。
在继续循环时如何保持之前投票的价值?
【问题讨论】:
-
您在循环内将整数初始化为 0。一旦您离开
if块,这些变量就会超出范围。如果你想保留它们,你必须在循环之外声明它们。 -
@JosephAndrews 您指的是我的回答,还是您的意思是回复 Arc676?
标签: java loops increment decrement