因此,当用户输入数字时,我正在运行一个程序,然后打印出该整数之前的奇数。
public class odd2 {
static Scanner UI = new Scanner(System.in);
public static void main(String[] args) {
{
// TODO Auto-generated method stub
System.out.print ( " Please enter a number ");
if (UI.hasNextInt() )
{
int numberEntered = UI.nextInt();
//define the limit
System.out.println("Printing Odd numbers between 1 and " + numberEntered);
for(int i=1; i < numberEntered; i++){
//if the number is not divisible by 2 then it is odd
if( i % 2 != 0){
System.out.print(i + ",");
}
}
目前,它会打印出所有数字,并在其后添加逗号。有什么办法可以跳过 ,.我的一个解决方案可能可以创建这些整数的数组,然后使用 stringToArray 但我想知道是否有更简单的东西我丢失了。
最佳答案
像这样的东西会起作用:
System.out.print( (i == numberEntered - 1 || i == numberEntered - 2) ? i : i + ",");
使用三元运算符检查“i”是否是最终值,然后仅打印数字。
关于Java - 从 for 循环输出数字时如何去掉最后一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104595/