[英]How do I replace the first three characters of a Java integer by 111?
[英]how to replace an integer array with characters in java
整数 = 0111254
将所有 0 替换为 'z'
用'p'替换奇数
用'q'替换偶数
output 应该是 zpppqpq
我的代码部分....
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);
}
它给出了错误的 output 的 qssss
您可以将 integer 转换为字符串,然后使用String.replace()
。
String numberString = ""+0111254;
// Replace all 0 chars with z
numberString.replace('0','z');
// etc...
您可以将数字转换为字符串,然后将字符串转换为数组,并通过使用 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.