本文介紹了如何將用戶輸入存儲在整數(shù)數(shù)組中?的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我不知道用戶將輸入多少個數(shù)字,我需要程序在數(shù)組到達(dá)行尾時(shí)停止在數(shù)組中插入數(shù)字,因?yàn)樵谛滦兄?,用戶將輸入一個與此無關(guān)的數(shù)字。
舉例:
用戶可以輸入:
1 5 7 8 9 5
4
或:
%5%4%8%9%4%2%1%3%2%4
7
我需要的數(shù)組是,例如1:[1,5,7,8,9,5]
推薦答案
如果您的需求允許您詢問用戶,您可以這樣做:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] num;
Scanner scanner=new Scanner(System.in);
System.out.print("How many integers you want to enter: ");
int n = 0;
if(scanner.hasNextInt()) {
n=scanner.nextInt();
}
num=new int[n];
for(int i=0;i<n;i++) {
System.out.printf("Enter integer %d: ",i+1);
if(scanner.hasNextInt()) {
num[i]=scanner.nextInt();
}
}
System.out.println(Arrays.toString(num));
}
}
示例運(yùn)行:
How many integers you want to enter: 3
Enter integer 1: 10
Enter integer 2: 15
Enter integer 3: 20
[10, 15, 20]
您也可以按如下方式操作:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] num;
Scanner scanner = new Scanner(System.in);
System.out.print("How many integers you want to enter: ");
int n = 0;
if (scanner.hasNextInt()) {
n = scanner.nextInt();
scanner.nextLine();
}
num = new int[n];
System.out.print("Enter the integers separated by a space: ");
String[] strNums = null;
if (scanner.hasNextLine()) {
strNums = scanner.nextLine().split(" ");
}
if (strNums != null) {
for (int i = 0; i < n; i++) {
try {
num[i] = Integer.parseInt(strNums[i]);
} catch (Exception e) {
System.out.println("Invalid input");
break;
}
}
System.out.println(Arrays.toString(num));
}
}
}
示例運(yùn)行:
How many integers you want to enter: 3
Enter the integers separated by a space: 10 15 20
[10, 15, 20]
但是,如果您希望整數(shù)數(shù)量不受限制,則應(yīng)該使用List
而不是數(shù)組(因?yàn)閿?shù)組的大小在初始化時(shí)是固定的),如下所示:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List <Integer> intList=new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the integers separated by a space: ");
String[] strNums = null;
if (scanner.hasNextLine()) {
strNums = scanner.nextLine().split(" ");
}
if (strNums != null) {
for (String strNum: strNums) {
try {
intList.add(Integer.parseInt(strNum.trim()));
} catch (Exception e) {
System.out.println("Invalid input");
break;
}
}
System.out.println(intList);
//You can even get an array out of the list as follows:
Integer[] nums = intList.toArray(new Integer[0]);
System.out.println(Arrays.toString(nums));
}
}
}
示例運(yùn)行:
Enter the integers separated by a space: 10 20 30 40
[10, 20, 30, 40]
[10, 20, 30, 40]
祝您一切順利!
這篇關(guān)于如何將用戶輸入存儲在整數(shù)數(shù)組中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,