简体   繁体   中英

Java fizzBuzz (excercise from CodingBat- Array2)

I have this fizzBuzz excercise from codingBat https://codingbat.com/prob/p153059 , my idea of solving is pretty basic:

public String[] fizzBuzz(int start, int end) {
  
  int n=end-start;
  
  String[] array=new String[n];
  
  for(int i=0;i<n;i++){
    
    if(((start+i) % 3 ==0) && ((start+i) % 5 ==0)) array[i]="FizzBuzz";
    if((start+i) % 5 ==0)  array[i]="Buzz";
    if((start+i) % 3 ==0)  array[i]="Fizz";
    
    
    else{
      array[i]=String.valueOf((start+i));
    }
  }
  
  return array;
  
}

I don't understand why at the if's part in the for loop only the bottom if is read so for example all numbers that are multiple of 3's as shown above will be displayed as "Fizz" but only them, then if i put a different if at the bottom, it will be the only one that is displayed, i can't seem to figure out why.

You are using only if statement which will check all the conditions, and if last condition(bottom if) is satisfied then it will print its output.

So, U will have to use if...else statement for that.

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