java - 修改java中的数组

标签 java arrays

所以我试图弄清楚如何通过 Scanner 对象获取用户输入,将其放置在数组的每个槽中,然后将这些数字读回给用户加一。问题是我必须使用循环来进行读回语句。这是我到目前为止所拥有的。我用扫描仪弄清楚了第一个循环,但我不知道如何使用循环修改数组中的每个元素。

import java.util.Scanner; 
public class Lab7 
{
public static void main(String [] Args)
{

    Scanner console = new Scanner(System.in);

    System.out.println("Enter your 5 integers: ");


    int index =0; 
    final int SIZE = 5; 
    int[] arrayOfSize = new int[SIZE]; 


    while(index<arrayOfSize.length )
    {
        arrayOfSize[index]=console.nextInt();
        index++; 

    }

    System.out.println("Processing each array element...");

最佳答案

您可以执行以下操作,这里我首先获取用户输入的整数并将其增加 1然后将其存储在a[]中它的整数数组代码是 int j = scanner.nextInt(); // store it in array as incremented by 1. a[i]=j+1; ,

我稍后会迭代以获取用户输入值+1,例如如果用户输入为1,则在数组中它将存储为2:-

完整的可运行代码如下,包含注释和示例输入和输出:-

public class SOTest {
    public static void main(String[] args) {
        // create scanner object
        Scanner scanner = new Scanner(System.in);
        // create an array of 10 integers
        int a[] = new int[10];
        for(int i=0;i<10;i++){
            int j = scanner.nextInt();
            // store it in array as incremented by 1.
            a[i]=j+1;
        }
        // Now array of integers have the user input value+1.
        for(int i=0;i<10;i++) {
            System.out.println(" "+ a[i]);
        }
    }
}

我的程序输入和输出如下,这将使其易于理解:-

1 2 3 4 5 6 7 8 9 11 printing user input value by adding 1 to it 2 3 4 5 6 7 8 9 10 12

关于java - 修改java中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748048/

相关文章:

c - C代码的指针

java - 在 CRUD 问题中添加功能时出现问题

java - 在 HTTP 请求 header 中插入用户凭据

arrays - 根据行重复 Numpy 数组可变次数

java - 检测哪个复选框被触摸?数组 Java Android Studio

c - 结构化类型数组初始化

c - 大数组声明时出现段错误

java - 当按下后退按钮时,我们可以用 bundle 保存线程吗?

java - Imgproc.cvtColor参数含义

java sax 程序不去 startElement() 方法