如何删除数组中的最后一个逗号和空格?爪哇 [英] How to remove last comma and space in array? Java
本文介绍了如何删除数组中的最后一个逗号和空格?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
伙计们,我想知道如何从数组中删除多余的逗号和空格?当我运行程序时,它给了我 {1, 2, 3, 4, 5, }.我想要的是{1, 2, 3, 4, 5}.Main 必须保持不变.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屋!
查看全文