【问题标题】:Why does the output stay 0 and -1, regardless the input?为什么不管输入,输出都保持 0 和 -1?
【发布时间】:2019-09-05 22:16:35
【问题描述】:

我是 java 新手,我正在尝试编写一个程序来获取未定义数量的整数并告诉你同一整数的最长顺序。

public class Search{
  public static void main(String args[]){


    int order[] = new int[args.length];
    for(int i = 0;i < args.length;i++){        //Input into array
      order[i] = Integer.parseInt(args[i]);
    }
    int count = 0;
    int temp_count = 0;
    int pos = -1;
    int temp_pos = -1;
    boolean search = false;

    for(int i = 1; i < args.length;i++){
      if(order[i-1] != order[i]){
        temp_count = 1;                    //line of the same integers?
        search = true;
        temp_pos++;
      } else if(search && order[i-1] == order[i]){ // How long is the line?
          temp_count++;
      } else if(search && order[i-1] != order[i]){ // Does the line end?
          if (temp_count > count){
            count = temp_count;             // Update old length and position
            pos = temp_pos;
          }
          search = false;
      }
    }
    System.out.println("length: " + count);    //output
    System.out.println("position " + pos);
  }
}

输出是 0 和 -1 ,只有在没有相同整数的顺序时才会出现这种情况。

【问题讨论】:

标签: java search


【解决方案1】:

在您的if 语句中,您检查了两次if 和else if 中的相同条件。
而且这种情况永远不会发生:

} else if(search && order[i-1] != order[i]){ 

这样所有变量都保持count = 0;和pos = -1;

  if(order[i-1] != order[i]){
    //...
  } else if(search && order[i-1] != order[i]){ 
    // never run!! 
    //...
    count = temp_count;     
    pos = temp_pos;  
  }

【讨论】:

  • 您的帮助。我意识到,我不需要第一个 if 语句,只需使用第二个语句来验证它是否是订单。
猜你喜欢
  • 2012-10-12
  • 2022-12-17
  • 1970-01-01
  • 2012-08-05
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多