例如,如果用户要输入“ABZ748FJ9K”作为字符串,我将如何查明该字符串的最大值(在本例中为 9),然后将其输出回用户。
任何非数字字符都应该被忽略。
我尝试做一些 if-else 梯子,但这需要我列出每个数字,而且它的行为方式无论如何都不是我想要的。我知道一定有更好的解决方案。一些帮助将不胜感激。谢谢!
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;
}
}
}
最佳答案
试试这个:
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","")
将通过替换所有非数字来确保字符串中的所有字符都是数字
-digit 字符,带有 ""
关于java - 如何找到字符串中的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902111/