java:给定一个字符串,在其中选择数字,按升序排序,然后打印结果
正如标题所示。例如,如果输入为java:给定一个字符串,在其中选择数字,按升序排序,然后打印结果,java,java.util.scanner,Java,Java.util.scanner,正如标题所示。例如,如果输入为9103ndhai*25ma@#$,则程序应输出012359。 这是我的尝试: public static void main (String args[]) { Scanner cin = new Scanner (System.in); String myString = ""; while (cin.hasNext()) { int tempInt = cin.nextInt(); myString =
9103ndhai*25ma@#$
,则程序应输出012359
。
这是我的尝试:
public static void main (String args[]) {
Scanner cin = new Scanner (System.in);
String myString = "";
while (cin.hasNext()) {
int tempInt = cin.nextInt();
myString = myString + tempInt;
}
Scanner intScan = new Scanner (myString);
List<Integer> intList = new ArrayList();
while (intScan.hasNext()) {
int tempInt2 = intScan.nextInt();
intList.add(tempInt2);
}
Collections.sort (intList);
for (int i=0; i<intList.size(); i++){
System.out.println(intList.get(i));
}
}
publicstaticvoidmain(字符串参数[]){
扫描仪cin=新扫描仪(System.in);
字符串myString=“”;
while(cin.hasNext()){
int tempInt=cin.nextInt();
myString=myString+tempInt;
}
Scanner intScan=新扫描仪(myString);
List intList=new ArrayList();
while(intScan.hasNext()){
int tempInt2=intScan.nextInt();
intList.add(tempInt2);
}
Collections.sort(intList);
对于(int i=0;i我详细阐述了您的代码并尝试使用它:
public static void main (String args[]) {
List<Integer> intList = new ArrayList();
Scanner cin = new Scanner(System.in);
System.out.println("Enter the sequence");//9103ndhai*25ma@#$
String myString = "";
String tempInt = cin.next();
for(int i = 0; i< tempInt.length(); i++){
String s = ""+tempInt.charAt(i);
if(s.matches("[0-9]"))
intList.add(Integer.parseInt(""+tempInt.charAt(i)));
}
Collections.sort (intList);
for (int i=0; i<intList.size(); i++){
System.out.print(intList.get(i));
}
}
publicstaticvoidmain(字符串参数[]){
List intList=new ArrayList();
扫描仪cin=新扫描仪(System.in);
System.out.println(“输入序列”);//9103ndhai*25ma@#$
字符串myString=“”;
字符串tempInt=cin.next();
对于(int i=0;i
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
Pattern p = Pattern.compile("\\d"); //Matches single digits (from 0-9) - prepend -? to the regex to react to "negative" digits
Matcher m = p.matcher(input);
List<Integer> integers = new ArrayList<Integer>();
while (m.find()) {
integers.add(Integer.parseInt(m.group()));
}
Collections.sort(integers);
integers.forEach(System.out::print);
}
publicstaticvoidmain(字符串参数[]){
扫描仪=新的扫描仪(System.in);
字符串输入=scanner.next();
Pattern p=Pattern.compile(\\d”);//将单个数字(从0-9)-prepend-?匹配到正则表达式,以对“负”数字作出反应
匹配器m=p.Matcher(输入);
列表整数=新的ArrayList();
while(m.find()){
add(Integer.parseInt(m.group());
}
集合。排序(整数);
整数.forEach(System.out::print);
}
General flow:读取字符串,对于字符串中的每个字符,如果是数字,计算出数字值,添加到列表中。最后,排序列表提示:根据示例输出使用hasnetint(),看起来您想要提取数字,而不是数字,对吗?是的,数字是我想要的,不是数字…sry用于混淆。