问题是: 得分为10人;然后你需要问每个人得分高于80,如果他想继续研究'y'为是和'n'为否。接下来你需要在数组中得到它们的位置,所以如果第5个数组[5] = 90并且回答“y”它将使用newarray创建一个新数组[1] = [5(他的位置)]
我的问题是如何在不了解其长度的情况下定义新阵列(将会有多少'y')。 修改
import java.util.Scanner;
public class p44_52 {
static Scanner reader = new Scanner(System.in);
static void input(int []a)
{
for(int i=0; i<a.length;i++){
System.out.println("Write an score of a student");
a[i]= reader.nextInt();
}
}
static void output(int []b)
{
for (int i =0; i<b.length;i++)
{
System.out.println("serial number of who choose to continue and score above 80 "+ b[i]);
}
}
public static void main(String[]args){
char c = 'g';
int count =0;
int []score = new int[10];
kelet(score);
for(int i=0; i<score.length;i++)
{
if(score[i]>80)
{
System.out.println("Studnet number "+i+ " Do you want to continue?");
c = reader.next().charAt(0);
if(c == 'y'){
//Here i want to make the new array(length isn't known) for their locationnumbers
}
}
}
}
}
答案 0 :(得分:2)
您可以创建一个与完整列表大小相同的临时数组(因为您知道它可能需要的最大数量),并使用尽可能多的学生填充它以继续。实际上临时数组中的元素可能会少于它可以容纳的元素,因为有些学生不会继续,所以你可以创建一个大小合适的新数组(现在你知道它)并使用System.arraycopy()来实现将所有元素复制到正确大小的数组中。
这不是最有效的方法,但它并不可怕(它只是使用一个额外的数组分配和复制操作),它对于家庭作业来说当然足够好。并且它不使用除数组之外的任何东西。
一般来说,这是一种在编写程序时会不时使用的技术:如果在完成某些操作之前有些事情是你无法做到的,那么找一种方法将操作分解为多个步骤,以便您可以按顺序重新排列步骤,但仍然会产生相同的结果。更好的方法是找到一个满足您需求的不同数据结构(因为ArrayList会在运行时增加容量),但是有时候你不能只是放入不同的数据结构,而这种方法打破问题并重新安排步骤可能会很有用。
答案 1 :(得分:1)
List<Integer> list= new ArrayList<Integer>();
list.add(10); //you can add elements dynmically.
//to get data you can use
list.get(0); //index at which you want data
答案 2 :(得分:0)
取决于您编程的语言。在java中,必须先声明数组中的空间量,然后才能使用它。这是因为Java为数组留出了空间。其他语言(如Python)不要求您声明使用的空间量。有很多方法可以在Java中解决这个问题,比如使用arraylist。
答案 3 :(得分:0)
使用arraylist。如果他说不,那么你将其删除。最后你
yourArrayList.toArray()
将arrayList转换为数组。
编辑:
public static void main(String[]args){
char c = 'g';
int count =0;
int []score = new int[10];
ArrayList<Integer> list = new ArrayList<Integer>();
kelet(score);
for(int i=0; i<score.length;i++)
{
if(score[i]>80)
{
System.out.println("Studnet number "+i+ " Do you want to continue?");
c = reader.next().charAt(0);
if(c == 'y'){
list.add(//your variable);
}
}
}
//If you want turn it into array
int [] listArray = list.toArray();
}
答案 4 :(得分:0)
的ArrayList
创建了Arraylists来解决数组的长度问题。
在你的例子中:
for(int i=0; i<score.length;i++)
{
if(score[i]>80)
{
System.out.println("Studnet number "+i+ " Do you want to continue?");
c = reader.next().charAt(0);
if(c == 'y'){
//Here i want to make the new array(length isn't known) for their locationnumbers
}
}
}
你想做这样的事情:
List<String> continueStudy = new ArrayList<String>();
for(int i=0; i<score.length;i++)
{
if(score[i]>80)
{
System.out.println("Studnet number "+i+ " Do you want to continue?");
c = reader.next().charAt(0);
if(c == 'y'){
continueStudy.add(c);
}
}
}
然后您可以使用for循环来评估每个字符串,例如:
for(String Value : continueStudy){
if(value.contains('y')){
//DO SOMETHING or call seperate function
}
}