[英]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.