這裏是我的代碼:如何維持前期增量的價值循環
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
這裏是我的問題:
比方說,我運行程序一次,我選擇投我的馬·羅哈斯投票。我輸入數字11.如果我選擇停止該計劃,它會對它進行合併,並說Mar Roxas得到一票,而另一個得到0.到目前爲止,這麼好。當我決定選擇繼續循環(將重新運行程序)時,它會出現問題。
當我決定投上其他政客我的投票,決定結束程序,我對馬·羅哈斯初始票變爲0,Duterte得到1
我怎樣才能保持我以前的票值當繼續循環?
您初始化整數0的循環中。只要你離開那個if區塊,那些變量就會超出範圍。如果你想保留它們,你必須在循環之外聲明它們。 – Arc676
@JosephAndrews您是指我的答案,還是您的意思是迴應Arc676? –