A very basic java outprint issue

cscscs :

I want a specific command to print on the same line but it prints on different lines and I can't figure out a simple fix for it.

package lab10;

import java.util.Scanner;

public class PrintArray {

    public static void main(String[] args) {


        int numItems;
        int[] items;


        Scanner scan = new Scanner (System.in);
        System.out.println("Enter the number of items");

        numItems = scan.nextInt(); 

        items = new int [numItems];

        if (items.length > 0);{
            System.out.println("Enter the value of all items"
                    + "(seperated by space):");
            for (int i = 0; i < items.length; ++i) {


                int val = scan.nextInt();
                items[i]= val;
            }
        }

        for (int i = 0; i < items.length; ++i) {
            if (i== 0) {
                System.out.println("The values are:" + items[i]);

            }else {
                System.out.println("The values are:" + items[i] + "," + " ");

            }
        }
    }
}

Expected result:

Enter the number of items

3

Enter the value of all items(separated by space):

1 2 3

The values are:1, 2, 3

Actual result:

Enter the number of items

3

Enter the value of all items(separated by space):

1 2 3

The values are:1

The values are:2,

The values are:3,

Elliott Frisch :

Instead of i == 0 you want items.length == 0, and "is" not "are". Also, you'll need additional logic to handle joining the values (and use System.out.print to avoid printing a newline). Like,

if (items.length != 0) {
    System.out.print("The values are: ");
}
for (int i = 0; i < items.length; ++i) {
    if (items.length == 1) {
        System.out.print("The value is: " + items[i]);
    } else {
        if (i != 0) {
            System.out.print(", ");
        }
        System.out.print(items[i]);
    }
}
System.out.println();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324190&siteId=1