简体   繁体   English

在Java中使用数组回显整数

[英]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. 我正在创建一个程序,该程序通过用户输入使用5个integers ,并在同一行上用空格分隔。 From there I need to assign these integers to an array and then echo the array back. 从那里,我需要将这些整数分配给array ,然后将array回显。

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} . 应该很简单,但是我遇到了困难,我的回声没有在整数之间插入空格,即用户输入的是{1 2 3 4 5}并且结果是12345 ,理想情况下应该是{1 2 3 4 5}

This is my first opportunity to play with arrays , so any assistance would be helpful! 这是我玩arrays第一个机会,因此任何帮助都会有所帮助!

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 尝试使用split代替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. Printf仅打印出现在引号或变量所包含的值中的内容。

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] );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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