我正在制作一个节目。我已经得到了我的最终结果,但没有得到所需的格式。我的要求是输出的格式应该是[z1,z2 ...]
public class Range {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input your frist number.");
int input1 = red(console);
System.out.println("Please input your second number.");
int input2 = red(console);
printRange(input1, input2);
}
public static int red(Scanner console) {
int x = console.nextInt();
return x;
}
public static void printRange(int input1, int input2) {
if (input1 > input2) {
for (int Z = input1; Z >= input2; Z--) {
System.out.print("[" + Z + "]");
}
}
else if (input1 < input2) {
for (int Z = input1; Z <= input2; Z++) {
System.out.print("[" + Z + "]");
}
}
else {
System.out.print("[" + input1 + "]");
}
}
}
答案 0 :(得分:1)
public static void printRange(int e, int r){
int [] result = new int[1];
if(e<r){
result = new int[r-e];
for(int i=0;i<(r-e);i++)
result[i]=e+i+1;
}else if(r<e){
result = new int[e-r];
for(int j=0;j<(e-r);j++)
result[j]=r+j+1;
}else
result[0]=e;
System.out.println(Arrays.toString(result));
}
答案 1 :(得分:-1)
尝试以下代码,希望这就是您所需要的:
import java.util.Scanner;
public class Range {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input your frist number.");
int input1 = red(console);
System.out.println("Please input your second number.");
int input2 = red(console);
printRange(input1, input2);
}
public static int red(Scanner console) {
int x = console.nextInt();
return x;
}
public static void printRange(int input1, int input2) {
System.out.print("[");
if (input1 > input2) {
for (int Z = input1; Z >= input2; Z--) {
if(Z != input1){
System.out.print( ", " );
}
System.out.print( Z );
}
} else if (input1 < input2) {
for (int Z = input1; Z <= input2; Z++) {
if(Z != input1){
System.out.print( ", " );
}
System.out.print( Z );
}
} else {
System.out.print( input1 );
}
System.out.print( "]" );
}
}
修改强> 说明:这是获取所需输出所需的内容。