简体   繁体   中英

Echoing Integers Using an Array with Java

I'm working to create a program that takes in 5 integers via user input, separated by spaces on the same line. From there I need to assign these integers to an array and then echo the array back.

Should be pretty straightforward, but I am having a tough time where my echo back is not inserting spaces between the integers ie, the users input is {1 2 3 4 5} and the result is 12345 , which should ideally be {1 2 3 4 5} .

This is my first opportunity to play with arrays , so any assistance would be helpful!

Below is the code I have written thus far:

package echo5ints;

import java.util.Scanner;

/**
 *
 * @author laure
 */
public class U7D1_Echo5Ints {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int i =0;
    int arr[]=new int[5];

    Scanner input = new Scanner(System.in);

    System.out.print("Please enter 5 numbers: ");

    String line = input.nextLine();
    Scanner numbers = new Scanner(line);

    for(i=0;i<5;i++) 
        arr[i]=numbers.nextInt();

    System.out.println("These were the 5 numbers entered: " + arr[0] + arr[1]  + arr[2]  + arr[3]  + arr[4] );
}
}

try using split instead and printf

System.out.print("Please enter 5 numbers: ");
String line = input.nextLine();
String [] arr = line.split (" ");
System.out.printf("These were the 5 numbers entered: %s %s %s %s %s", 
              arr[0], arr[1], arr[2], arr[3], arr[4] );

The spaces you seems to have added is for code and not for print statements.

Printf only print what appears inside quotes or the values held by variables.

SO your print line should be

  System.out.println("These were the 5 numbers entered: " + arr[0] +" "+ arr[1] +" " + arr[2] +" " + arr[3] +" " + arr[4] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM