如何删除数组中的最后一个逗号和空格?爪哇 [英] How to remove last comma and space in array? Java

查看:301
本文介绍了如何删除数组中的最后一个逗号和空格?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我想知道如何从数组中删除多余的逗号和空格?当我运行程序时,它会给我{1,2,3,4,5,}.我想要的是 {1,2,3,4,5}.主必须保持不变.我需要帮助的是PrintArray方法.

guys I was wondering how to remove the extra comma and space from the array? When I run the program it gives me {1, 2, 3, 4, 5, }. What I want is {1, 2, 3, 4, 5}. Main must stay the same. PrintArray method is the one I need help with.

引用重复的问题陈述. 这是不同的,因为它要求用户输入数字并相应地打印数组.这不是重复的问题.

Referring to duplicate question statement. This is different because it asks a user for a number and prints the array accordingly. This is not a duplicate question.

    public static void printArray(int[] myArray)
    {

        System.out.print("[");
        for(int i = 0; i < myArray.length; i++)
        {
            myArray[i] = i + 1;
            System.out.print(myArray[i] + ", ");
        }
        System.out.println("]");
    }
}

推荐答案

不要首先打印它.仅在i > 0时才在字符串前打印逗号.

Don't print it in the first place. Print the comma before the string and only when i > 0.

public static void printArray(int[] myArray)
{

    System.out.print("[");
    for(int i = 0; i < myArray.length; i++)
    {
        myArray[i] = i + 1;
        if (i > 0)
        {
            System.out.print(", ");
        }
        System.out.print(myArray[i]);
    }
    System.out.println("]");
}

这篇关于如何删除数组中的最后一个逗号和空格?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆