简体   繁体   English

JAVA -我如何编写带有字母和数字的转换(小写->大写,单个数字->其值的两倍,两位数字->其数字总和)程序?

[英]JAVA -How do I write a converting (lowercase->uppercase, single digits->double its value, two digits->sum of its digits) program w/ letters & numbers?

I was tasked to write a function that takes in user input as a string.我的任务是编写一个将用户输入作为字符串接收的函数。 For all characters which are numeric, double its value and, if it is two digits, then replace it with the sum of its digits (eg, 6 → 12 → 3 whereas 3 → 6).对于所有数字字符,将其值加倍,如果是两位数字,则将其替换为其数字之和(例如,6 → 12 → 3 而 3 → 6)。 For all characters which are in uppercase, replace it with lowercase.对于大写的所有字符,将其替换为小写。 For all characters which are in lowercase, replace it with uppercase (eg, m → M and N → n).对于所有小写的字符,将其替换为大写(例如,m → M 和 N → n)。 The program should keep asking the user to enter strings until they either enter 'q' or 'Q' to quit.程序应不断要求用户输入字符串,直到他们输入“q”或“Q”退出。 I have this so far, which works for the conversion of the letters.到目前为止,我有这个,它适用于字母的转换。 I'm not sure how to implement the other part into it and where it would go.我不确定如何将另一部分实施到其中以及它会去哪里。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String str1;
    System.out.print("Enter string: ");
    str1 = scan.nextLine();
    StringBuffer newStr = new StringBuffer(str1);

    for (int i = 0; i < str1.length(); i++) {

        //Checks for lower case character
        if (Character.isLowerCase(str1.charAt(i))) {
            //Convert it into upper case using toUpperCase() function
            newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
        }
        //Checks for upper case character
        else if (Character.isUpperCase(str1.charAt(i))) {
            //Convert it into upper case using toLowerCase() function
            newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
        }
    }

    System.out.println("String after conversion : " + newStr);
}

} }

here is my approach这是我的方法


    public static String conversion(String inputString){
        String out = "";
        for(char c:inputString.toCharArray()){
            if(Character.isDigit(c)){
                int num = Integer.parseInt(String.valueOf(c))*2;
                if(num>=10){
                    char[] parts = String.valueOf(num).toCharArray();
                    int sum = 0;
                    sum+=Integer.parseInt(String.valueOf(parts[0]));
                    sum+=Integer.parseInt(String.valueOf(parts[1]));
                    out+=sum;
                }else out+=num;
            }else{
                if(Character.isUpperCase(c)) out+=Character.toLowerCase(c);
                else out+=Character.toUpperCase(c);
            }
        }
        return out;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM