请帮助我的教授教学不好 我的教授希望我用户将输入其索引和元素的值我尝试做2循环,但它不会工作
import java.util.Scanner;
public class Arrays
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int index;
int elements;
System.out.println("Input Array Size");
index = sc.nextInt();
for (int i = 0; i < index; i++)
{
System.out.println("Array Index is =\t"+index);
System.out.println ("Insert the Elements of the Array");
break;
}
}
}
如果有人知道这方面的链接,请发送给我我非常需要你的帮助我需要学习输入搜索和删除数组,但使用扫描仪干草请帮助我 - 学生
答案 0 :(得分:1)
您还需要在for循环中扫描输入。请查看以下代码
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Input Array Size : ");
int size = sc.nextInt();
int[] elements = new int[size];
System.out.println("Insert "+size+" Elements of the Array");
for (int i = 0; i < size; i++) {
System.out.print("Element "+i+" : ");
elements[i] = sc.nextInt();
}
System.out.println("Provided array:" + Arrays.toString(elements));
} finally {
sc.close();
}
}
答案 1 :(得分:0)
这里的问题是你只是打印数组大小,而不是接受任何输入来填充数组。实际的方法如下。
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
//Create a Scanner to read input
Scanner scan = new Scanner(System.in);
//Promt the user to enter the array size and store the input
System.out.println("Enter the size of the array:");
int arraySize = scan.nextInt();
//Create an array (For this example we'll use an integer array)
int[] array = new int[arraySize];
//Create a for loop to run through array
for(int i = 0; i < arraySize; i++)
{
//Prompt the user to enter a number at the current index (i)
System.out.println("Enter the element at index " + i + ":");
//Store the input at index i in the array
array[i] = scan.nextInt();
}
}
}