简体   繁体   中英

What's wrong in this Code? Netbeans not compiling the code

What's wrong with this piece of code? I am trying to solve a question where we have 2 strings and we have to print how many times we can extract the second string from the first one. When I am running this code, my Netbeans did not responding, it is taking about time in seconds like 25 seconds, 30 seconds like this.

public class nine {
  static int res=0;

  public static void main(String[] args) {
    int c=0;

    String as="nniinneetteeeenn";       // first string

    String ss = "nineteen";             // second string
    char a[]= ss.toCharArray();
    char b[]= as.toCharArray();
    boolean result = true; 

    while(result == true){
      for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
          if(a[i]==b[j]){
            b[j]=32;
            res=1;
            break;
          }
        } //j loop ends

        if(res==0)
          break;
      } // i loops ends

      if(res==0)
          result=false;

      else{
          result=true;
             c++;
         }
      } // while loops ends       

      System.out.println(c);
  }
}
if(res==0)
    result=false;

Will never execute and therefore your while loop will never terminate.

The reason it will never execute is because res will never be re-assigned to zero once your for loop begins.

It will work only if you do not have any matches. Once the res is changed to other than 0. It has no possibility to change back to 0. That's why if your code finds any match then it will go to an infinite loop.

Because once the res = 1 is executed you never re-assigned it to 0 again. that's why when it executed res = 1 it goes to an infinite loop

Edited You can do this, in your else part just reset res to 0

    else{
        result=true;
        c++;
        res=0;
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM