[英]The second method call won't excute (java)
我正在嘗試制作一個簡單的骰子程序,該程序需要用戶輸入他們想要擲骰子的邊數和骰子數,並為每個骰子輸出擲骰子。 我包含一個while循環,該循環允許用戶重新滾動相同數量的骰子,且邊數相同,而不必重新輸入以前輸入的信息。 我遇到的問題是,當我在“ while”循環的“ if”語句中調用“ q”方法時,骰子無法重新滾動。 忠告?:
import java.util.Random;
import java.util.Scanner;
public class Choice_Dice {
static int t = 0, sides, c=0, d =0;
public static void main(String [] Mack){
Scanner scan = new Scanner(System.in);
String y ="y";
System.out.println("You may roll a dice with any number of sides");
System.out.println("Enter the number of sides you would like to the dice to have: ");
sides = scan.nextInt();
System.out.println("Enter the number of dice you want to roll: ");
t = scan.nextInt();
q();
while(y.equals("y"))
{
System.out.println("Would you like to roll again(y or n): ");
y = scan.next();
if(y.equals("y")){
q();
}
else
System.out.println("Thanks");
}
}
public static void q()
{
int[] x = new int[t];
c = 0;
while(c != t)
{
x[c] = roll(sides);
c++;
}
while(d != t)
{
System.out.println("You rolled " + x[d]);
d++;
}
}
public static int roll(int s)
{
Random generator = new Random();
int dice = 0;
dice = generator.nextInt(4) + 1;
return dice;
}
}
問題出在
while(d != t)
{
System.out.println("You rolled " + x[d]);
d++;
}
在打印卷筒的同時,將d
遞增至4。 當此方法結束時,您的while
循環將起作用,並輸入"y"
。 當再次調用該方法時, d
值為4
,為什么t
值為4
所以d == t
。 您需要重置它或使用適當的for
循環進行迭代。
丑陋的做法是
public static void q()
{
int[] x = new int[t];
c = 0;
while(c != t)
{
x[c] = roll(sides);
c++;
}
while(d != t)
{
System.out.println("You rolled " + x[d]);
d++;
}
d = 0;
}
漂亮的方法是
public static void q()
{
int[] x = new int[t];
for (int i = 0; i < x.length ; i++) {
x[i] = roll(sides);
System.out.println("You rolled " + x[i]);
}
}
因此,現在您擺脫了x
和c
static
變量。 您還可以通過一些簡單的重構擺脫t
。
您沒有使用sides
的方式。
這取決於您對d
的使用。 您記得要重置c
的值,但不要重置d
。
public static void q()
{
// Init variables
int[] x = new int[t];
c = 0;
d = 0;
while(c != t)
{
x[c] = roll(sides);
c++;
}
while(d != t)
{
System.out.println("You rolled " + x[d]);
d++;
}
}
沒有理由c
和d
應該是靜態類變量。 相反,您應該只在方法調用中聲明它們,就像使用x
:
public static void q()
{
// Init variables
int[] x = new int[t];
int c = 0;
int d = 0;
while(c != t)
{
x[c] = roll(sides);
c++;
}
while(d != t)
{
System.out.println("You rolled " + x[d]);
d++;
}
}
您可以針對while循環嘗試這種邏輯
while(true)
{
System.out.println("You may roll a dice with any number of sides");
System.out.println("Enter the number of sides you would like to the dice to have: ");
sides = scan.nextInt();
System.out.println("Enter the number of dice you want to roll: ");
t = scan.nextInt();
q();
System.out.println("Would you like to roll again(y or n): ");
y = scan.next();
if(y.equals("n")){
System.out.println("Thanks");
break;
}
}
還要檢查方法q()的邏輯:您需要在那里重置值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.