簡體   English   中英

我如何使我的答案看起來像[z1,z2…]

[英]How do i make my answer look like [z1, z2 …]

我正在做一個程序。 我已經達到了最終結果,但不是必需的格式。 我的要求是輸出的格式應為[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 + "]");
        }
    }
}
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));
}

嘗試以下代碼,希望這是您需要的:

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( "]" );
    }
}

編輯:說明:這是獲取所需輸出所需要的。

  1. 當您說希望將所有數字括在[]中時,您要做的就是將方括號移出循環,以便僅打印一次。 在添加數字之前用大括號括住,在數字添加之后用括號括住。
  2. 如果要在方括號中添加字符串列表,則需要在兩個數字之間使用分隔符(,)。 因此,我在添加每個數字之前添加了一條打印語句。 if條件限制在第一個數字之前添加分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM