Home > Enterprise >  Problem with returning a string, nothing is returned while storing max and min
Problem with returning a string, nothing is returned while storing max and min

Time:04-07

   public static String highLow(String s) {
            String high = " ";
            String low = " ";
            int max = -10000;
            int min = 10000;
            char[] c = s.toCharArray();
            for(int i = 0; i<c.length; i  ){
                if(c[i]>=max){
                    max = (int)c[i];
                    high = Character.toString(c[i]);
                }
                if(c[i]<=min){
                    min = (int)c[i];
                    low = Character.toString(c[i]);
                   
                }
               
                
            }
       return high   " "   low;
}
    

Statement of problem: Create a method that accepts a string of space separated numbers and returns the highest and lowest number (as a string). My problem is that it only returns the value of highest string, for example: System.out.println(highLow("1 2 3 4 5")); only returns 5

CodePudding user response:

HERE IS THE EDITTED VERSION

    int max = 0, min = 0;
    String s = "1 2 3 4 5";
    StringTokenizer spaces = new StringTokenizer(s, " ");
    min = max = Integer.parseInt(spaces.nextToken());
    while(spaces.hasMoreTokens())
    {
        int number = Integer.parseInt(spaces.nextToken());
        if(number > max)
            max = number;
        if(number < min)
            min = number;
    }
    System.out.print(Integer.toString(min)   " "   Integer.toString(max));

^^THIS WORKS^^

I am not fluent with ASCII values(yet!) but I know that you can convert the String value into integers that can be compared numerically.

int value;   
for(int i = 0; i < s.length(); i  = 2)
{
    value = Integer.parseInteger(
                Character.toString(s.charAt(i)));
}

EDIT: I WILL LEAVE THIS HERE FOR IDEAS BUT YOU CANNOT PARSE INTEGER VALUES FROM CHARACTERS! YOU WERE ON THE MONEY WITH THE (int) MASK facepalm haha

CodePudding user response:

There are a couple of problems with your code. First of all s.toCharArray() is not appropriate here since it does not get rid of spaces and won't work with numbers that have more than one digit. Instead, you should consider splitting the String and parsing its elements to int. What you are describing sounds a lot like a school or university assignment, so I won't give away the whole solution, but consider the splitting your input string using s.split(" ") and parsing the resulting elements using Integer.parseInt(someStringNumber), where you insert your single numbers after splitting. Also, just to make sure you can handle any numbers (within the value range of integers), consider initializing your min and max variables with Integer.MAX_VALUE and Integer.MIN_VALUE, respectively.

  • Related