如何接受来自用户的java参数

我试图让用户在此函数中输入 2 个字符串,以便可以比较它们。


我对 Java 不太熟悉,更熟悉 C++,而且我不是开发人员。


public class Levenshtein {


    public static int distance(String a, String b) {

        a = a.toLowerCase();

        b = b.toLowerCase();

        // i == 0

        int [] costs = new int [b.length() + 1];

        for (int j = 0; j < costs.length; j++)

            costs[j] = j;

        for (int i = 1; i <= a.length(); i++) {

            // j == 0; nw = lev(i -1, j)

            costs[0] = i;

            int nw = i - 1;

            for (int j = 1; j <= b.length(); j++) {

                int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);

                nw = costs[j];

                costs[j] = cj;

            }

        }

        return costs[b.length()];

    }


    public static void main(String [] args) {

        String [] data = { "kitten", "Mitten" };

        for (int i = 0; i < data.length; i += 2)

            System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));

    }

}


慕姐4208626
浏览 171回答 4
4回答

墨色风雨

只需使用argsin mainpublic static void main(String [] args) {&nbsp; &nbsp; for (int i = 0; i < args.length; i += 2)&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("distance(" + args[i] + ", " + args[i+1] + ") = " + distance(args[i], args[i+1]));}并运行它java -jar app.jar kitten mitten

慕盖茨4494581

下面是如何使用Scanner读取 Java 输入的示例。Scanner s = new Scanner(System.in);String first = s.nextLine();String second = s.nextLine();String[] nextTwo = s.nextLine().split(" ");System.out.println(first);System.out.println(second);System.out.println(nextTwo[0]);System.out.println(nextTwo[1]);s.close();样本输入我是一个茶壶又矮又粗这是我的把手示例输出我是一只茶壶又矮又粗这是至于如何在您的程序中应用它,只需执行以下操作:public static void main(String [] args) {    // Using this construct, the "try-with-resources" block, will automatically    // close the Scanner resource for you    try(Scanner s = new Scanner(System.in) {        System.out.println("Enter first word:");        String first = s.nextLine();        System.out.println("Enter second word:");        String second = s.nextLine();        System.out.println(String.format("The distance is: %d",distance(first, second)));    }//Scanner s is automatically closed here}请注意,您通常不应该关闭System.in流,因为它不允许您在程序的其余部分读取输入。但是,由于您的程序在 try-with-resources 块的范围内终止,因此在这种情况下这样做是可以接受的。

慕容708150

您可以使用扫描仪对象:Scanner myObj = new Scanner(System.in);&nbsp; // Create a Scanner objectSystem.out.println("Enter username");String userName = myObj.nextLine();&nbsp; // Read user input

慕村225694

我使用扫描仪从控制台输入。你可以这样做:Scanner sc = new Scanner(System.in);String s1 = sc.nextLine();String s2 = sx.nextLine();System.out.println("distance(" + s1 + ", " + s2 + ") = " + distance(s1, s2));sc.close();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java