![](/img/trans.png)
[英]How do i store multiple user inputs (String,Int,Double) in an array/arraylist and output the stored data(Java)?
[英]How do I store the user input that is indented by a space into the String array and convert the number into int array?
我對編程並不陌生,但是在將用戶輸入存儲到字符串數組並將其存儲到 int 數組時遇到了問題。 有人知道如何修復我的代碼嗎? 或者還有其他方法嗎?
我想將此輸入存儲到一個單獨的 int 數組和一個字符串數組中。
用戶輸入:
“T 3”
“V 4”
《問 19》
預期結果:
數字[0] = 3
數字[1] = 4
數字[2] = 19
商店[0] =“T”
商店[1] = "V"
商店[2] = "Q"
此代碼創建一個超出范圍的索引:
線程“主”java.lang.ArrayIndexOutOfBoundsException 中的異常:索引 1 超出長度 1 的范圍
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
問題是您正在調用input.next()
,它返回下一個標記,由空格分隔。 因此,令牌本身不能包含任何空格。 所以.split(" ")
方法調用總是會返回一個單元素數組,所以只有一個paint[0]
,沒有paint[1]
。 目前尚不清楚您要在代碼中實現什么; 如果您擴展問題,您可能會得到更多答案。
更新:既然您已經向我們展示了您的輸入和預期結果,我認為您需要做的是:
store[i] = input.next();
num[i] = input.nextInt();
input.next() 僅在您采用 String 數據類型時才有效,但在這里您采用 int 作為數據類型,因此它在這里不起作用。
試試這個
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
檢查這個。 在您的代碼中進行了微小的更改。
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.