编写一个程序,显示两个数字在1到7范围内的所有组合,其中两个位置不能以相同的数字显示。显示可能的组合数量。(例如,允许(1.2),(2.1),但不允许组合(1,1),(2,2)...)。
有人可以给我一些提示吗?我是Java新手。我不知道该怎么做。谢谢!
我用这个程序作为解决问题的主意。
public class PossibleCombinations {
public static void main(String[] args) {
int[] input = { 1, 4, 3 };
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 3; z++) {
if (x != y && y != z && z != x) {
System.out.println(input[x] + "" + input[y] + "" + input[z]);
}
}
}
}
}
}
幸运的是,在我的情况下效果不佳,这是我的代码:
public class Domaci17 {
public static void main (String[] args) {
new Domaci17();
}
public Domaci17() {
int[] unos = {1,2,3,4,5,6,7};
for (int a = 0; a <= 7; a++ ) {
for (int b = 0; b <= 7; b++ ) {
for (int c = 0; c <= 7; c++ ) {
for (int d = 0; d <= 7; d++ ) {
for (int e = 0; e <= 7; e++ ) {
for (int f = 0; f <= 7; f++ ) {
for (int g = 0; g <= 7; g++ ) {
if (a != b && b != c && c != d && d != e && e != f && f != g && g != a) {
System.out.println(unos[a] + "" + unos[b]);
System.out.println(unos[b] + "" + unos[c]);
System.out.println(unos[c] + "" + unos[d]);
System.out.println(unos[d] + "" + unos[e]);
System.out.println(unos[e] + "" + unos[f]);
System.out.println(unos[f] + "" + unos[g]);
System.out.println(unos[g] + "" + unos[a]);
}
}
}
}
}
}
}
}
}
}
public class Domaci17 {
public static void main (String[] args) {
new Domaci17();
}
public Domaci17() {
int[] unos = {1,2,3,4,5,6,7};
for (int a = 0; a <= 7; a++ ) {
for (int b = 0; b <= 7; b++ ) {
if (a != b ) {
System.out.println(unos[a] + "" + unos[b]);
}
}
}
}
}
当我“剪切”代码时,我得到12、13、14、15、16、17。但是如何获得其他组合?(21,23,24 .... 27)(31,...... 37)(41,.... 47)(51,..... 57)(61 ... 67)( 71 ...... 76)
请更清楚地陈述您的问题。据我了解您的问题,您可能想做这样的事情-
public static void main(String[] args) throws Exception {
for(int i=1;i<8;i++){
for(int j=1;j<8;j++){
if(i!=j){
System.out.println(i+","+j);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句