문제

For example, if a user were to input "ABZ748FJ9K" as a string, how would I pinpoint the max value of that string (in this case it is 9), and then output it back to the user.

Any non-numeric character is supposed to be ignored.

I tried doing some if-else ladder, but that would require me to list out every number, and it wasn't behaving the way I wanted it to anyways. I know there must be a better solution. Some help would be greatly appreciated. Thanks!

import java.util.Scanner;

public class Question{

public static void main(String args[]){   

   Scanner input = new Scanner(System.in);

   System.out.println("Please enter a string");
      String userInput = input.next();

   int finalMax = max(userInput);

   System.out.println("The maximum value is " + finalMax);


}

public static int max(String s){

int x = s.length();

int y = 0;

   for (int i=0; i < x; i++){

         if (s.charAt(i) == 9){
            y=9;
         }
         else if (s.charAt(i) == 8){
            y=8;
         }
    }

return y;

}


}





    }
도움이 되었습니까?

해결책

Try this:

public static int max(String s){
    s=s.replaceAll("\\D","");
    int x = s.length();  
    int y = Character.getNumericValue(s.charAt(0));

    for (int i=1; i < x; i++){  
         if (Character.getNumericValue(s.charAt(i)) > y){
            y=Character.getNumericValue(s.charAt(i));
         }
    }    
    return y;   
}

s=s.replaceAll("\\D","") will make sure all character in your string is a digit by replacing all non-digit character with ""

다른 팁

Use the function below instead of your version:

public static int max(String s){

int x = s.length();

int y = 0;
Character temp = null;
   for (int i=0; i < x; i++){
      char ch = s.charAt(i);

         if (ch >= '0' &&  ch <='9' && (temp == null || temp < ch )){
            temp = s.chartAt(i);         
         }      
    }

return Integer.valueOf(temp);

}

Start a max value with 0, then u will loop the string. Each loop u must verify if it is char or int, if int then check if it is > than the max value, if so, set the new max value.

I leave as a challenge to u, to think about each position of the string will be treated as a char.

Cheers. Good luck.

you should try something like:

public static int max(String s){
  int max = -1;
  char current;
  for(int i = 0; i<s.length; i++){
    current = s.charAt(i);
    if(current > '0' && current < '9')
      if(current > max) 
        max = current;
  }
  return max;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top