1

So I'm running a program when a user is inputting a number and then I am printing out the odd numbers that come before this integer.

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 + ",");
                }
        }

Currently it prints out all numbers with a comma after them. Is there any way I can skip the ,. A solution I've though that might work it to create an array of these integers and then use stringToArray but I'd like to know if there is something easier I am missing.

JavaSprinter
  • 61
  • 1
  • 6

1 Answers1

1

Something like this would work:

System.out.print( (i == numberEntered - 1 || i == numberEntered - 2) ? i : i + ",");

Using a turnary operator to check if 'i' is the final value, then only printing the number.

Liam Ferris
  • 1,786
  • 2
  • 18
  • 38