我使用冒泡排序方法按顺序(最少到最大)对输入数字进行排序,我在自己的方法中使用它。然后,在下一个方法(我需要按顺序排列数字)中,似乎忽略了我已经在前一个方法中对数字进行了排序。我没有正确地调出方法或者什么? 谢谢!
import java.util.Scanner;
public class hw6 {
public static int getOrder(int n1, int n2, int n3, int n4, int n5) {
Scanner in = new Scanner(System.in);
if (n1>n2){
int t = n1;
n1 = n2;
n2 =t;
}
if (n2>n3){
int t = n2;
n2 = n3;
n3 =t;
}
if (n3>n4){
int t = n3;
n3 = n4;
n4 =t;
}
if (n4>n5){
int t = n4;
n4 = n5;
n5 =t;
}
if (n1>n2){
int t = n1;
n1 = n2;
n2 =t;
}
if (n2>n3){
int t = n2;
n2 = n3;
n3 =t;
}
if (n3>n4){
int t = n3;
n3 = n4;
n4 =t;
}
if (n1>n2){
int t = n1;
n1 = n2;
n2 =t;
}
if (n2>n3){
int t = n2;
n2 = n3;
n3 =t;
}
if (n1>n2){
int t = n1;
n1 = n2;
n2 =t;
}
System.out.println(n1+" "+n2+" "+n3+" "+n4+" "+n5);
return n1+n2+n3+n4+n5;//cards now in order from least to greatest
}
public static int getRank(int n1, int n2, int n3, int n4, int n5) {
int order;
int rank = 1;
order = getOrder(n1, n2, n3, n4, n5);
if (n1 == n2 && n1 == n3 && n1 == n4 ||
n2 == n3 && n2 == n4 && n2 == n5)
System.out.println("Four of a kind");
else if (n1 == n2 && n1 == n3 && n4 == n5 ||
n1 == n2 && n3 == n4 && n3 == n5)
System.out.println("Full house");
else if (n2 == n1+1 && n3 == n2+1 && n4 == n3+1 && n5 == n4+1)
System.out.println("Straight");
else if (n1 == n2 && n1 == n3 || n2 == n3 && n2 == n4 ||
n3 == n4 && n3 == n5)
System.out.println("Three of a kind");
else
System.out.println("A high card");
return rank;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n1, n2, n3, n4, n5; //input
int order;
int rank;
System.out.print("Enter (1-13):");
n1 = in.nextInt();
System.out.print("Enter (1-13):");
n2 = in.nextInt();
System.out.print("Enter (1-13):");
n3 = in.nextInt();
System.out.print("Enter (1-13):");
n4 = in.nextInt();
System.out.print("Enter (1-13):");
n5 = in.nextInt();
order = getOrder(n1, n2, n3, n4, n5);
rank = getRank(n1, n2, n3, n4, n5);
}
}
答案 0 :(得分:2)
Java是按值传递的,因此getOrder
方法接收值的副本。本地副本已更改,但main
的原始变量未更改。
要使更改保持不变,我会创建一个数组或ArrayList
来包含值。然后将其传递给您的方法以更改这些值。该方法将接收引用的副本到数组或ArrayList
对象,因此更改将保留在对象中。