Java 程序将数组的所有元素加一

编写一个 Java 程序,使用 for 循环将数组的所有元素加一。在这个 Java 示例中,for 循环将迭代数组元素,并在其中,我们将每个数组元素加一。

package NumPrograms;

import java.util.Scanner;

public class ArrayEleIncrementOne1 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i;
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter the Array size = ");
		Size = sc.nextInt();
		
		int[] arr = new int[Size];
		
		System.out.format("Enter the Array %d elements : ", Size);
		for(i = 0; i < Size; i++) 
		{
			arr[i] = sc.nextInt();
		}
	
		for(i = 0; i < arr.length; i++) 
		{
			arr[i] = arr[i] + 1;
		}
		
		System.out.println("\nThe Final Array After Incremented by One");
		for(i = 0; i < arr.length; i++) 
		{
			System.out.print(arr[i] + "   ");
		}
	}
}
Java Program to Increment All Elements of an Array by One

我们在此 Java 示例 中删除了额外的 for 循环,并在赋值时就增加了数组元素。

package NumPrograms;

import java.util.Scanner;

public class ArrayEleIncrementOne2 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i;
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter the Array size = ");
		Size = sc.nextInt();
		
		int[] arr = new int[Size];
		
		System.out.format("Enter the Array %d elements : ", Size);
		for(i = 0; i < Size; i++) 
		{
			arr[i] = sc.nextInt();
			arr[i] = arr[i] + 1;
		}
		
		System.out.println("\nThe Final Array After Incremented by One");
		for(i = 0; i < arr.length; i++) 
		{
			System.out.print(arr[i] + "   ");
		}
	}
}
Please Enter the Array size = 7
Enter the Array 7 elements : 13 33 54 76 34 98 11

The Final Array After Incremented by One
14   34   55   77   35   99   12   

使用 while 循环将数组的所有元素加一的 Java 程序。

package NumPrograms;

import java.util.Scanner;

public class ArrayEleIncrementOne3 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i;
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter the Array size = ");
		Size = sc.nextInt();
		
		int[] arr = new int[Size];
		
		System.out.format("Enter the Array %d elements : ", Size);
		i = 0;
		while(i < Size) 
		{
			arr[i] = sc.nextInt();
			arr[i] = arr[i] + 1;
			i++;
		}
		
		System.out.println("\nThe Final Array After Incremented by One");
		i = 0;
		while(i < arr.length) 
		{
			System.out.print(arr[i] + "   ");
			i++;
		}
	}
}
Please Enter the Array size = 8
Enter the Array 8 elements : 11 22 33 44 55 66 77 88

The Final Array After Incremented by One
12   23   34   45   56   67   78   89