数组输入保存在所有位置

时间:2016-01-06 14:39:29

标签: java arrays position

我有一个代码,我试图在数组中保存输入,但是当我这样做时,保存所有位置。 如果我的用户输入是Klas,Philip和Comp i得到输出:

Klas Philip来自Comp,编号为100

Klas Philip来自Comp,编号101加入

来自Comp的Klas Philip添加了102号

来自Comp的Klas Philip添加了103号

但是我确实希望第一个用户输入从Comp中保存为Klas Philip,添加了数字100,第二个输入保存在101号,依此类推。 但是现在Comp的第一个输入Klas Philip保存了所有数字

这是代码

    Class1[] all = new Class1[120];
    int quantity = 0;

        System.out.println("text: ");
        String x = keyboard.nextLine();

        System.out.println("text2:  ");
        String y = keyboard.nextLine();

        System.out.println("text 3: ");
        String z = keyboard.nextLine();

        Class1 p = new Class1(x, y, z);
        all[quantity++] = p;

        for (int i = 100; i < all.length; i++)
             System.out.println(p.getFirstName()+(" ")+p.getSurname()+" from " +p.getTeamName()+" with number " +(x) +" added");

        if (quantity == all.length){
            Class1[] temp = new Class1[all.length * 2];
            for (int i = 0; i < all.length; i++)
                temp[i] = all[i];
            all = temp;

    }
}   

}

1 个答案:

答案 0 :(得分:0)

我发现很难弄清楚你想要达到的目标。你能编辑一下这个问题,使它更清晰吗?您将Class1数组的长度硬编码为120,这就是您重复打印的原因。

更改

for (int i = 100; i < all.length; i++)
     System.out.println(p.getFirstName()+(" ")+p.getSurname()+" 
     from " +p.getTeamName()+" with number " +(x) +" added");

for (int i = 100; i < all.length; i++)
     System.out.println(p.getFirstName()+(" ")+p.getSurname()+" 
     from " +p.getTeamName()+" with number " +(i) +" added");

获取您描述的输出,即:

  1. Klas Philip来自Comp,编号为100
  2. Klas Philip来自Comp,编号101加入
  3. 除非您的意思是

    1. Klas Philip来自Comp,编号为100
    2. 来自Gallifrey的Tom Baker,编号为101
    3. 在这种情况下,我会先将每个用户输入存储在数组或List中,然后循环遍历它以将其打印出来。 E.g:

        Scanner keyboard = new Scanner(System.in);
        List<Class1> all = new ArrayList<Class1>();
        int quantity = 0;
        while(quantity <2) // whatever the max number of entries should be
        {
      
              System.out.println("text: ");
              String x = keyboard.nextLine();
      
              System.out.println("text2:  ");
              String y = keyboard.nextLine();
      
              System.out.println("text 3: ");
              String z = keyboard.nextLine();
      
              Class1 p = new Class1(x, y, z);
              all.add(p);
              quantity++;
          }
              for (int i = 0; i < all.size(); i++)
                   System.out.println(all.get(i).getFirstName()+(" ")+
                   all.get(i).getSurname()+" from " +all.get(i).getTeamName()+" with number 
                   " +(i) +" added");
      

      控制台输出:

      text: 
      Jan
      text2:  
      Klaas
      text 3: 
      Huntelaar
      text: 
      Tom
      text2:  
      Baker
      text 3: 
      Gallifrey
      Jan Klaas from Huntelaar with number 0 added
      Tom Baker from Gallifrey with number 1 added