简体   繁体   English

如何用 java 中的字符替换 integer 数组

[英]how to replace an integer array with characters in java

int = 0111254整数 = 0111254

replace all 0 with 'z'将所有 0 替换为 'z'

replace odd integers with 'p'用'p'替换奇数

replace even integers with 'q'用'q'替换偶数

The output should be zpppqpq output 应该是 zpppqpq

My part of the code....我的代码部分....

public static void main(String[] args) {
    int num;
    Scanner sc=new Scanner(System.in);
    num=sc.nextInt();
    int temp;
    int b[]=new int[10];
    char a[]=new char[10];


    for(int i=0;i<b.length;i++) {
        while(num!=0)
        {
            temp=num%10;

            b[i]=temp;

            num=num/10;
        }
    }

    for(int i=0;i<b.length;i=i+2)
    {
        if(b[i]==0)
        {
            b[i]=115;
        }

        else if(b[i]%2!=0)
        {
            b[i]=113;
        }
        else if(b[i]%2==0) {
            b[i]=112;
        }
    }

    for(int i=0;i<a.length;i++)
    {
        a[i]=(char)b[i];
    }

    for(int i:a)
    {
        System.out.print((char)i);
    }

it gives a wrong output of qssss它给出了错误的 output 的 qssss

You could turn that integer into a string and then use String.replace() .您可以将 integer 转换为字符串,然后使用String.replace()

String numberString = ""+0111254;
// Replace all 0 chars with z
numberString.replace('0','z');
// etc...

you can take the numbers into a string and then convert strings into an array, and by using a for loop, take the single number and parse into integer, then apply your logic.您可以将数字转换为字符串,然后将字符串转换为数组,并通过使用 for 循环,将单个数字解析为 integer,然后应用您的逻辑。

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] ary = String.valueOf(sc.next()).split("");

        StringBuilder answer = new StringBuilder();

        for (String n : ary) {
            int value = Integer.parseInt(n);
            if (value == 0) {
                answer.append("z");
            } else if (value % 2 == 0) {
                answer.append("q");
            } else {
                answer.append("p");
            }
        }

        System.out.print(answer.toString());
    }

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

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