我正在尝试创建一个Java程序,该程序读取键盘输入的数字字符串,
并给出最长的升序子字符串。
以下是我的代码:
import java.util.Scanner;
public class Ascending{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number = ");
String n = in.nextLine();
int length = n.length();
for(int i = 0; i < length; i++) {
char first = n.charAt(i);
char next = n.charAt(i+1);
char last = n.charAt(length-1);
int f = (int)(first - 48);
int nx = (int)(next - 48);
int l = (int)(last - 48);
if (f<nx) {
String asc = n.substring(i, i++);
i++;
System.out.println("output = " + asc);
}
else {
String asc = n.substring(i, i++);
System.out.println("output = " + asc);
break;}
}
}
}
<Enter a number = 12 output = >
最佳答案
您正在使用后增量运算符,但我认为您没有尝试观察它是如何工作的。尝试这个:
int i = 0;
System.out.println(i);
System.out.println(i++);
System.out.println(i);
0
0
1
++
)说“递增此值,然后在递增之前返回该值”。n.substring(i, i++);
i == i++
)。++i
,但是在代码高尔夫之外很少使用它,因此最终会使人们感到困惑。 IMO的最佳实践是仅在自己的行上使用++
并避免查看返回值。n.substring(i, i+1);
https://stackoverflow.com/questions/15457509/