java - 执行此功能的更好或更标准的方法是什么?

标签 java loops if-statement methods do-while

我是一名java初学者,在这个特定的问题中,我练习编写一个程序,将任何给定的字符串转换为小写字符串。 java中有没有更好的方法来实现这个目标(在设计方面)?

此外,“else”(在“else if”之后)如何捕获或等待我进行输入。不知怎的,这部分对我来说没有意义,尽管我实现了我想要的。输入中的“ans”值如何传输到整个循环并使用直到循环关闭?

经过多次尝试和失败,我对转换部分使用了单独的方法。我的第二个问题有点太复杂,无法研究。

import static java.lang.System.out;
import java.util.Scanner;

public class MyClass {

    public static Scanner s = new Scanner(System.in);
    public static String ans;

    public static void main(String args[]) {
        Conversion();

        do {
            ans = new String(s.nextLine());

            if (ans.equalsIgnoreCase("Y")) {
                Conversion();
            } else if (ans.equalsIgnoreCase("N")) {
                out.println("Thank you for using this program!");
                break;
            } else {
                out.println("Invalid entry!");
                out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
            }

        } while (ans != "N");

    }//END MAIN

    public static void Conversion() {
        out.println("Please enter string to be converted to lowercase: ");
        String str = new String(s.nextLine());
        out.println("Your new string is: " + str.toLowerCase());
        out.println("Would you like to convert another string? (Y/N)");
    }

}

最佳答案

我注意到一些问题; Conversion 看起来像一个类名(Java 命名约定为 conversion),并且 ans != "N" 使用 == 而不是 .equals - 并且不会忽略大小写 (!ans.equalsIgnoreCase("N"))。全局变量(例如static)不好(将Scanner传递给需要它的方法),并且静态导入 只是让代码更难以推理(在我看来)。您当前的循环并不真正遵循传统形式,我会提取提示和循环以将“另一个”转换为新方法,如果您必须打印感谢,我会在“主循环”之后这样做。比如,

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);

    do {
        conversion(sc);
    } while (another(sc));
    System.out.println("Thank you for using this program!");
}

public static void conversion(Scanner s) {
    System.out.println("Please enter string to be converted to lowercase: ");
    System.out.printf("Your new string is: %s%n", s.nextLine().toLowerCase());
}

public static boolean another(Scanner s) {
    while (true) {
        System.out.println("Would you like to convert another string? (Y/N)");
        String ans = s.nextLine();
        if (ans.equalsIgnoreCase("Y")) {
            return true;
        } else if (ans.equalsIgnoreCase("N")) {
            return false;
        }
        System.out.println("Invalid entry!");
        System.out.println("(Please type 'Y' for yes, or 'N' for no.)");
    }
}

关于java - 执行此功能的更好或更标准的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57517316/

相关文章:

php - 如何使用php在json文件中查找数据

python - 遍历 numpy.array 的任意维度

r - if/else 构造内部和外部函数

c++ - 使用赋值作为条件表达式?

javascript - 为什么javascript将0视为空字符串?

java - ReSTLet引用解码 "#"符号

JavaFX 边框不适合具有自定义形状的节点

sql - 如何迭代点以将线串拆分为 PgSQL 中的部分?

java - 仅当未设置时才排除 SerializedName 字段

java - eclipse Java;导出 jar,包括引用的库,没有 fatjar