是否有一个“问题”;“修剪”;类似于java中整数循环的方法?
我正在使用for循环打印一组整数,但我不希望最后一个数字后面有空格。我注意到这个字符串有类似trim的东西,但是我还没有找到一个线程讨论循环中整数的类似trim的方法 下面是我的代码的一小部分:是否有一个“问题”;“修剪”;类似于java中整数循环的方法?,java,loops,trim,removing-whitespace,Java,Loops,Trim,Removing Whitespace,我正在使用for循环打印一组整数,但我不希望最后一个数字后面有空格。我注意到这个字符串有类似trim的东西,但是我还没有找到一个线程讨论循环中整数的类似trim的方法 下面是我的代码的一小部分: for(int i = 0; i < size.length; i++){ System.out.print("Enter the numbers you want in the array "); size[i] = scanner.nextInt();
for(int i = 0; i < size.length; i++){
System.out.print("Enter the numbers you want in the array ");
size[i] = scanner.nextInt();
}
min = size[0]; // I had to initialize this after the program knew how big the array would be
for(int i = 0; i < size.length; i++){
System.out.print(size[i] + " ");
}
for(int i=0;i
字符串输出=”;
对于(int i=0;i您只需将打印设置为有条件:
for(int i = 0; i < size.length; i++){
if(i == size.length -1){
System.out.print(size[i]);
} else {
System.out.print(size[i] + " ");
}
}
我会推荐Tyler和hermitmaster的解决方案,但如果您对空格没有问题,可以创建一个新字符串并继续连接整数,然后使用trim()方法去除前导空格和尾随空格,然后打印它
for(int i = 0; i < size.length; i++){
System.out.print("Enter the numbers you want in the array ");
size[i] = scanner.nextInt();
}
min = size[0];
String result = ""; // temporary variable to store integers.
for(int i = 0; i < size.length; i++){
result += size[i] + " "; // concatenate integers to string
}
System.out.println(result.trim()); // removes leading and trailing white space.
for(int i=0;i
请在问题中包含您的源代码。您可能需要执行String.valueOf(yourInteger.strip())
数字末尾的空格是什么?如果你只是打印出来,末尾就没有空格了。分享你的代码,这样我们就可以看到发生了什么。我没有在这个问题上得到反对票。如果你投反对票,请添加评论。太好了。我不习惯迭代器语法。我们在课堂上没有讨论过,但希望很快就能看到。谢谢!我喜欢使用I因为它可以帮助我避免列表迭代错误,这意味着我不必在我的代码中都使用名为“I”和“j”的整数:)在StringBuilder或StringBuffer中构建字符串要快得多。编译器可以在一个表达式中完成所有操作,但不能跨越多个语句。@Jerry101我同意,但为了简单起见,我使用了字符串连接。这一点很好。编程初学者最好以后再学习这些细节。
boolean first = true;
for(int val : size){
if(first){
System.out.print(val);
first = false;
} else {
System.out.print(" " + val);
}
}
for(int i = 0; i < size.length; i++){
System.out.print("Enter the numbers you want in the array ");
size[i] = scanner.nextInt();
}
min = size[0];
String result = ""; // temporary variable to store integers.
for(int i = 0; i < size.length; i++){
result += size[i] + " "; // concatenate integers to string
}
System.out.println(result.trim()); // removes leading and trailing white space.