【问题标题】:displaying multiple array variables显示多个数组变量
【发布时间】:2017-06-26 17:17:00
【问题描述】:

此程序获取 2 个团队和 2 个结果的用户输入,用“:”分隔符将它们分隔,然后将它们存储在数组中,当用户输入“停止”一词时,它会停止询问用户输入,并且旨在显示比赛的结果和统计数据(尚未添加到代码中)。我遇到的问题是,如果我输入多行匹配结果然后输入“停止”,它只会将用户输入的第一行显示回控制台而不显示其他任何输入?输入示例:“切尔西:阿森纳:2:1”。

public static final String SENTINEL = "stop";

public static void main(String args[]) {

    Scanner sc = new Scanner(System.in);

    String hometeam = new String();
    String awayteam = new String();
    String homescore = new String();
    String awayscore = new String();

    int result0;
    int result1;

    System.out.println("please enter match results:");

    // loop, wil ask for match results ( b < () )
    for (int b = 0; b < 100; b++) {

        String s = sc.nextLine();

        // stop command
        while (sc.hasNextLine()) { // better than the for loop

            String line = sc.nextLine();

            String results[] = s.split(" : "); // parse strings in between
                                                // the

            for (String temp : results) {
                hometeam = results[0];
                awayteam = results[1];
                homescore = results[2];
                awayscore = results[3];
            }

            // convert 'score' strings to int value.
            result0 = Integer.valueOf(results[2]);
            result1 = Integer.valueOf(results[3]);

            if ("stop".equals(line)) {
                System.out.println(Arrays.toString(results));
                return; // exit
            }

【问题讨论】:

  • 您在 while 语句的每次迭代中声明和初始化 results,所以它总是不同的。
  • 为什么是for (String temp : results) {
  • 我是从另一个 stackoverflow 问题中得到的,它有效,所以我把它留在了
  • 您可能断章取义了。如果你只是复制/粘贴代码而不理解它,你永远不会学会自己编码。

标签: java arrays loops delimiter


【解决方案1】:

它输出您输入的第一个结果的原因是因为results 被分配给s.split(" : ")s 在外部 for 循环的第一次迭代中永远不会改变,所以 s.split(" : ") 永远不会改变。您的results 始终保留第一个匹配结果!

你的代码写得很错误。

首先,为什么在 for 循环中有一个 while 循环? for 循环是多余的。

其次,您不能为此使用数组。试试ArrayList。数组无法动态改变其大小。

第三,我建议你为此创建一个类,代表MatchResult

class MatchResult {
    private String homeTeam;
    private String awayTeam;
    private int homeScore;
    private int awayScore;

    public String getHomeTeam() {
        return homeTeam;
    }

    public String getAwayTeam() {
        return awayTeam;
    }

    public int getHomeScore() {
        return homeScore;
    }

    public int getAwayScore() {
        return awayScore;
    }

    public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
        this.homeScore = homeScore;
        this.awayScore = awayScore;
    }

    @Override
    public String toString() {
        return "MatchResult{" +
            "homeTeam='" + homeTeam + '\'' +
            ", awayTeam='" + awayTeam + '\'' +
            ", homeScore=" + homeScore +
            ", awayScore=" + awayScore +
            '}';
    }
}

然后,您可以创建一个ArrayList&lt;MatchResult&gt; 来存储用户输入。

Scanner sc = new Scanner(System.in);

String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();

System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop

    String line = sc.nextLine();
    if ("stop".equals(line)) {
        System.out.println(Arrays.toString(list.toArray()));
        return; // exit
    }
    String results[] = line.split(" : "); // parse strings in between

    hometeam = results[0];
    awayteam = results[1];
    homescore = Integer.valueOf(results[2]);
    awayscore = Integer.valueOf(results[3]);

    list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}

【讨论】:

    【解决方案2】:

    尝试添加另一个数组

    string[] matches = new string[]{};
    

    然后将您的值输入到数组中。我正在使用 b 因为那是循环中的 int 变量。我还输入了 +" :"

    matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
    

    然后将打印更改为

    System.out.println(Arrays.toString(matches));
    

    我认为这应该可行,但我无法对其进行测试。

    public static final String SENTINEL = "stop";
    
    public static void main(String args[]) {
    
        Scanner sc = new Scanner(System.in);
        string[] matches = new string[]{};
        String hometeam = new String();
        String awayteam = new String();
        String homescore = new String();
        String awayscore = new String();
    
        int result0;
        int result1;
    
        System.out.println("please enter match results:");
    
        // loop, wil ask for match results ( b < () )
        for (int b = 0; b < 100; b++) {
    
            String s = sc.nextLine();
    
            // stop command
            while (sc.hasNextLine()) { // better than the for loop
    
                String line = sc.nextLine();
    
                String results[] = s.split(" : "); // parse strings in between
                                                    // the
    
                for (String temp : results) {
                    hometeam = results[0];
                    awayteam = results[1];
                    homescore = results[2];
                    awayscore = results[3];
                }
    
                // convert 'score' strings to int value.
                result0 = Integer.valueOf(results[2]);
                result1 = Integer.valueOf(results[3]);
    
                matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
    
                if ("stop".equals(line)) {
                    System.out.println(Arrays.toString(matches));
                    return; // exit
                }
    

    【讨论】:

      【解决方案3】:

      这是一个简单的循环,用于从用户那里获取所有数据,直到输入“停止”并显示输入的输出

          Scanner sc = new Scanner(System.in);
          ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
          System.out.println("please enter match results:");
          while(sc.hasNextLine())
          {
              String input = sc.nextLine();
              String[] results = input.split(" : ");
              if(results.length == 4)
              {
                  stats.add(results);
              }
              else if(input.equals("stop"))
                  break;
              else
                  System.out.println("Error reading input");
          }//end of while
      
          for(int i = 0; i < stats.size(); i++)
          {
              try{
                  System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
                      Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
              }catch (Exception e) {
                  //do nothing with any invalid input
              }
          }
      

      输出

      please enter match results:
      r : b : 5 : 4
      r : c : 7 : 10
      j : g : 3 : 9
      stop
      r vs b : 5 - 4
      r vs c : 7 - 10
      j vs g : 3 - 9
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多