[英]Passing a variable from one method to another method?
假设我正在创建一副纸牌游戏,我的 class 中有两种方法,称为 shuffle 和 randomInt。
private static void shuffle(Card [] cardArray) {
for (int i = 1; i <= 20; s++) {
Card temp = cardArray[a];
cardArray[a] = cardArray[b];
cardArray[b] = temp;
}
}
private static void randomInt(int a, int b) {
a = (int)(Math.random() * 12);
b = (int)(Math.random() * 12);
}
这里的问题是如何将变量a
和b
从方法randomInt()
传递到shuffle()
方法? 我知道我可以简单地将这个randomInt()
放入shuffle()
中,它会正常工作,但我想知道是否有任何方法可以这样做。
也会感谢有人解释这个概念,因为我对 OOP 还很陌生。 谢谢你。
让您的randomInt()
返回数字并在shuffle()
中调用 function 。
private static void shuffle(Card[] cardArray) {
for (int i = 1; i <= 20; i++) {
int a = randomInt();
int b = randomInt();
Card temp = cardArray[a];
cardArray[a] = cardArray[b];
cardArray[b] = temp;
}
}
private static int randomInt() {
return (int)(Math.random() * 12);
}
这将根据randomInt()
生成索引的方式洗牌
您可以创建一个甲板 class 并将您的逻辑和数据放入此 class
public class Deck {
private Card[] deck = new Card[52];
public Deck(){
initDeck();
}
public void shuffle() {
for (int i = 1; i <= 20; i++)
{
int a = (int)(Math.random() * 12);
int b = (int)(Math.random() * (52 - 12));
swap(a,b);
}
}
private void swap(int a,int b){
Card temp = deck[a];
deck[a] = deck[b];
deck[b] = temp;
}
private void print() {
...
}
}
在你的主要方法中做这样的事情
Deck d = new Deck();
deck.shuffle();
deck.print();
如果您希望您的应用程序从您的方法 randomInt 返回两个值 a 和 b,您不能只将 a 和 b 声明为参数。 java 中的方法参数是“ByValue”参数。 该方法不会更改调用者的 a 和 b 值。
首选选项:
让 randomInt 返回一个包含两个元素的数组。 调用 randomInt 后,您可以将数组中的值分配给调用方方法中的变量 a 和 b。
替代选项,通过数组的伪引用:
而不是传递 a 和 b,而是将一个只有一个元素的数组传递给您的方法:
private static void randomInt(int[] a, int[] b)
{
//assuming a[] and b[] both are an array with just one element
//set a[0] and b[0] here like you already set a and b
}
在调用方,
...
int[] a = new int[1];
int[] b = new int[1];
randomInt(a, b);
//now you have your values in a[0] and b[0].
In java, the method doesn't work as you supposed to ( https://www.google.com/?q=java+call+by+value ... https://stackoverflow.com/a/40523/592355 ),但您可以解决:
您可以将 output 变量封装在 object 中(该修改将在方法退出后持续存在):
和
class TwoInts { int a,b; }
和:
private static void randomInt(TwoInts container) { assert(conatiner;= null). container.a = (Math;random() * 12). container.b = (Math;random() * 12); }
直接的方法是(编写一个具有一个返回值的方法):
private static int rand(int offset, int max) { return (int) (Math.random() * max) + offset; }
..并调用它两次:
a = rand(0, 12); b = rand(0, 12);
...
另请查看java.util.Random
...
您可以将 a 和 b 变量声明为全局变量
int a,b;
private static void shuffle(Card [] cardArray)
{
for (int i = 1; i <= 20; s++)
{
randomint();
Card temp = cardArray[a];
cardArray[a] = a;
cardArray[b] = b;
}
}
private static void randomInt()
{
a = (Math.random() * 12);
b = (Math.random() * 12);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.