一起添加数组元素

时间:2015-12-16 20:08:49

标签: java

正如你所看到的,元素[1]和元素[2]都被转换为整数,我想知道是否有可能在每次while循环转换时加在一起。例如,元素1是每个游戏的得分,所以我想知道是否可以将每个游戏得分加在一起以获得用户输入的所有游戏的总得分。

import java.util.Scanner;
public class REQ1
{
    public static void main (String[] args) 
    {

     String playername;      
     String line;
     String[] list = new String[100];
     int count = 0;  
     int score;
     int time;


     Scanner sc = new Scanner(System.in); 


      System.out.println("Please enter your name");

      playername = sc.nextLine();

      System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");

      while (count < 100){

             line = sc.nextLine();

             if(line.equals("quit")){
                  break;
                  }

             list[count]=line;
            System.out.println("list[count]" + list[count]);

            count++;

         }   

        System.out.println("Player : "+playername);
        System.out.println("--------------------------------");
      for (int i=0; i<count; i++){
          line=list[i];
          String[] elements =line.split(":");             
          score=Integer.parseInt(elements[1].trim());
          time=Integer.parseInt(elements[2].trim());



          System.out.println("Game:" +elements[0]+ " Score= "+elements[1]+" Minutes Played= "+elements[2]);

      }



}


}

2 个答案:

答案 0 :(得分:0)

是的,这绝对是可能的。 你可以做这样的事情

      int totalScore = 0; //INITIAlISE THE VAR TOTAL SCORE
      for (int i=0; i<count; i++){
      line=list[i];
      String[] elements =line.split(":");             
      score=Integer.parseInt(elements[1].trim());
      time=Integer.parseInt(elements[2].trim());
      totalScore = totalScore + score;// ADD THIS LINE


          System.out.println("Game:" +elements[0]+ " Score= "+elements[1]+" Minutes Played= "+elements[2]);

      }

答案 1 :(得分:0)

      score+=Integer.parseInt(elements[1].trim());
      time+=Integer.parseInt(elements[2].trim());