将数组元素添加到一起



正如您在下面看到的,元素[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]);
      }

}

}
是的,这是绝对可能的。你可以做一些类似的事情
      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]);
      }
      score+=Integer.parseInt(elements[1].trim());
      time+=Integer.parseInt(elements[2].trim());

最新更新