如何解决无输出问题-使用while-?

时间:2019-04-23 09:21:33

标签: java

我尝试阅读“ Mi4”的每个字符 如果是字母,则将其放在变量“大写”中 如果是数字,则将其放入变量“ num”中 没有错误,也没有输出“

public static void main(String[] args) {
    String capital = "";
    int num = 1;
    String sentence = "Mi4";
    int senLength = sentence.length();
    int i = 0;
    while (i < senLength) {
        String senStr = sentence.substring(i, i + 1);
        char senChar = senStr.charAt(i);
        if (senChar >= 'A' && senChar <= 'Z') {
            capital = senStr;
        } else if (senChar >= 'a' && senChar <= 'z') {
            capital = capital + senStr;
        } else if (senChar >= '2' && senChar <= '9') {
            num = Integer.parseInt(senStr);
        }
        i++;
        sentence = sentence.substring(i);
    }
    System.out.println(capital);
    System.out.println(num);
}

2 个答案:

答案 0 :(得分:0)

您可以尝试这段代码,我从您的代码中可以理解的是,您必须遍历String的字符并分离出字符和数字。

因此,循环使用while循环直到使用charAt(index)的长度和获取字符就足够了。

始终使用StringBuffer / StringBuilder代替附加String。您可以浏览此link

如果要在Integer中解析字符,则将其转换为字符串,然后转换为Integer。您可以看到注释的代码。

public static void main(String[] args) {
        //String capital = "";
        //int num = 1;
        String senStr = "Mi4";
        int senLength = senStr.length();
        int i = 0;

        StringBuffer chBr =new StringBuffer();
        StringBuffer numBr =new StringBuffer();
        while (i < senLength)
        {
            char senChar = senStr.charAt(i);
            if (senChar >= 'A' && senChar <= 'Z')
            {
                chBr.append(senChar);
            }
            else if (senChar >= 'a' && senChar <= 'z')
            {
                chBr.append(senChar);
            }
            else if (senChar >= '2' && senChar <= '9')
            {
                //num =Integer.parseInt(String.valueOf(senChar));
                numBr.append(senChar);
            }
            i++;
            //sentence = sentence.substring(i);
        }
        System.out.println(chBr.toString());
        System.out.println(numBr.toString());
    }

答案 1 :(得分:0)

我已经尝试过您的代码,下面提到的解决方案有很多错误

String capital="";
int num=1;
String sentence= "Mi4";
int senLength= sentence.length();
int i=0;
while (i < senLength)//; in the while loop
{
    //String senStr=sentence.substring(i,i+1);  substring should be of 1st letter so (i,i+1) doesnot find letter in next iteration 
    char senChar= senStr.charAt(i);
    if (senChar >= 'A' && senChar <='Z')
    {capital= senStr;}
    else if (senChar >= 'a' && senChar <='z')
    {capital= capital+senStr;}
    else if (senChar >='2' && senChar<='9')
    {num= Integer.parseInt(senStr);}
    i++;
    //sentence=sentence.substring(i);same here in next iteration the string doesnot contains same lenght so it doesnot find char at i
}
System.out.println(capital);
System.out.println(num);