在不知道n值的情况下获取用户输入的n值
问题描述:
我想从用户读取n个值,但我不知道n的值。第二种情况{11,22,77,43,2,1,2111,322} 假设我想读取10个整数来自用户的值(第二次5 int int 值)(取决于每种情况)。在不知道n值的情况下获取用户输入的n值
第二件事是我想将这个值存储在一个数组中。
我真的被这个困住了。 任何帮助?
我尝试以下代码 -
int a[50],i=-1;//how to dynamically assign memory to an array
Scanner s=new Scanner(System.in);
do{
a[++i]=s.nextInt();
}while(!hasNextLine());
答
试试这个:
import java.io.*;
public class Hey
{
public static void main(String ar[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";//get the input
while((input = br.readLine()) != null)
{
String []numbers = input.split(",");
System.out.println(numbers.length);
}
}
}
答
如何为用户打算指示输入已完成?输入的格式如何? 我想:
- 用户输入一个整数为每行或由空格分隔的整数列表。
- 用户输入一个空行或与Intege不同的东西表示它已完成。
您需要一个ArrayList,因为在开始请求输入之前您不知道输入的数量。 ArrayList是动态的,所以你可以添加内容到它之前没有声明它的大小。
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while(s.hasNextInt()){
list.add(s.nextInt());
}
答
根据我的理解使用这个。
public static void main(String[] args){
int a[] = null;
int i = 1;
Scanner s=new Scanner(System.in);
while (s.hasNextLine()){
int temp[] = null;
if(a!=null){
temp = a;
}
a = new int[i];
a[i-1]=s.nextInt();
if(temp!= null){
for(int j=0;j<temp.length;j++){
a[j]=temp[j];
}
}
i++;
}
}
+0
什么时候while循环终止? –
+0
如果没有输入。 –
为什么不向用户询问数字并将其分配给可用作数组大小的最终变量? –
其实这是面试问题先生。我正在为它做准备。问题在不知道n值的情况下给出。 –
如果n未知,那么您需要一个动态大小的集合,如List。 –