![](/img/trans.png)
[英]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.