java - Java : Longest Ascending substring

我正在尝试创建一个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 = >

没有任何结果。

我假设在for循环中出了点问题,但是我无法弄清楚到底是哪里出了问题。

恐怕我可能定义了太多不必要的变量?

最佳答案

您正在使用后增量运算符,但我认为您没有尝试观察它是如何工作的。尝试这个:

int i = 0;

System.out.println(i);
System.out.println(i++);
System.out.println(i);

你会得到
0
0
1

这是因为后递增(++)说“递增此值,然后在递增之前返回该值”。

所以当你要求
n.substring(i, i++);

您明确要求一个长度为0的字符串(因为i == i++)。

您可以使用pre-increment运算符++i,但是在代码高尔夫之外很少使用它,因此最终会使人们感到困惑。 IMO的最佳实践是仅在自己的行上使用++并避免查看返回值。

真的,你想要的是
n.substring(i, i+1);

https://stackoverflow.com/questions/15457509/

相关文章:

Excel VBA 错误 - 函数或接口(interface)标记为受限。或函数使用 Visual

qt - 无法运行编译qt应用程序。 Qt Creator忽略斜线

compiler-errors - 在NME中定位-演示项目无法转换为例如JavaScript-目标

scala - 斯卡拉(Scala),卡斯巴(Casbah): MongoCollection.in

c++ - 无法解析的外部符号C++-错误的声明?

android - NDK错误: “can' t resolve `.data.rel.ro.loc

c++ - C++如何向minGW添加库

c++ - OpenCV无法编译

java - 升序子字符串编译错误

compiler-errors - 这怎么了? Submit.CommandText = SQL?