Intro Java Fencepost/While loops Conitional Tests -


i've been trying answer problem night, think brain fried midterms answer correctly. question [quoted]: write method highlow accepts integer parameter , returns whether or not number has alternating "high" , "low" digits. 0 through 4 "low" digits , 5 through 9 "high" digits. method should return true if number passed alternates between "high" , "low" digits, , false if not. may assume number passed positive. if number passed consists of single digit, method should return true.

note: method returns true if number alternates starting "high" digit or starting "low" digit. important digits alternate. example, both highlow(9292) , highlow(2929) should return true.

here example calls method , resulting return values:

call value returned highlow(1918193) true highlow(7283) true highlow(3827) true highlow(9388) false highlow(895151) false highlow(707) true highlow(44) false highlow(45) true highlow(5) true may not use string solve problem

and recent attempt:

     public class practeese {      public static void main(string[] args) {   highlow(1918193);    highlow(7283);   highlow(3827);;   highlow(9388);       highlow(895151);     highlow(707);   highlow(44);   highlow(45);     highlow(5);   }   public static boolean highlow(int n) {       // boolean ishigh = true;     //  boolean islow = true;       boolean test = true;       while (n > 0) {            boolean ishigh = true;           boolean islow = true;               if (n % 10 >= 5) {                    ishigh = true;               } else if (n%10<=5) {                    islow = true;               } else  {                        return false;                 }                n = n / 10;        if (n % 10 == 0 && (islow!= ishigh)) {         test = true;       } else {         test = false;       }    }   return test;  } } 

i understand fencepost style of question can seem solve it.. appreciated.

you need reach false once , can return - because other numbers not matter. need check if result true - compared previous number. can that:

public static boolean highlow(int n) {            boolean islasthigh= n % 10 >= 5 ; //first number check - don't compare           n=n/10; // start checking next numbers , see if high-low-high-low // if condition not met - return false , stop checking. otherwise keep going           while (n > 0) {                    if (n % 10 >= 5) {                       if(islasthigh)                          return false; //two highs in row                       islasthigh = true;                   } else {                       if(!islasthigh)                          return false; //two lows in row                       islasthigh = false;                   }                    n = n / 10;       }   return true; //we never returned false numbers until have been high-low-high , result true       } 

Comments