我的if用于将人名从小写转换为大写或反之亦然的程序中的小写不起作用

时间:2015-07-06 06:34:26

标签: java

我正在尝试制作一个将人名从小写转换为大写的java程序,反之亦然。这是我到目前为止的代码。我的问题是小写if语句不起作用,我不确定我做错了什么。我是新手,这是我用工作代码得到的最远的。我想保持代码简单,因为这和我到目前为止学到的差不多。此外,欢迎任何关于如何缩短此代码的建议。感谢

import java.util.Scanner;

public class ChangeCase {

    public static void main(String[] args) {
        System.out.print("Enter your first name:  ");
        Scanner scanFirstName = new Scanner(System.in);
        String firstName = scanFirstName.next();

        System.out.print("Display your name in uppercase(U) "
                + "or lowercase (L)?  Enter U or L:  ");

        Scanner scanChoice = new Scanner(System.in);

        String choice = scanChoice.next();

        if (choice.equalsIgnoreCase("u")) {
            if (choice.equalsIgnoreCase("l")) {
                String lower = firstName.toLowerCase();
                System.out.println("Your first name in lowercase is: " + lower);
            } else {
                String upper = firstName.toUpperCase();
                System.out.println("Your first name in uppercase is: " + upper);
            }
        } else {
            System.out.println("Invalid entry - must be U or L.");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

刚刚修改了你的条件。 这是工作代码。

if (choice.equalsIgnoreCase("l")) {
    String lower = firstName.toLowerCase();
    System.out.println("Your first name in lowercase is: " + lower);
} else if(choice.equalsIgnoreCase("u")){
    String upper = firstName.toUpperCase();
    System.out.println("Your first name in uppercase is: " + upper);
}
else {
    System.out.println("Invalid entry - must be U or L.");
}

小写检查的条件

  

if(choice.equalsIgnoreCase(“l”))

嵌套在大写的条件内。我把它移出来使这两个条件平行。

答案 1 :(得分:1)

使用此代码作为代码....修改了If-else块...

import java.util.Scanner;

public class ChangeCase {
public static void main(String[] args) {
    System.out.print("Enter your first name:  ");
    Scanner scanFirstName = new Scanner(System.in);
    String firstName = scanFirstName.next();

        System.out.print("Display your name in uppercase(U) "
                + "or lowercase (L)?  Enter U or L:  ");

        Scanner scanChoice = new Scanner(System.in);

        String choice = scanChoice.next();

        if (choice.equalsIgnoreCase("u")) {
            String upper = firstName.toUpperCase();
            System.out.println("Your first name in uppercase is: " + upper);
        }
        else if (choice.equalsIgnoreCase("l")) {
                String lower = firstName.toLowerCase();
                System.out.println("Your first name in lowercase is: " + lower);
            } 
        else {
            System.out.println("Invalid entry - must be U or L.");
        }
    }
}