[英]How to replace an integer with a character, arrays, loops, Java
我是 Java 的新手,目前,我正在學習 arrays 和循環。 我有一項任務,但我不知道該做什么,我需要一些幫助。
寫個星星class。
在這個class中,聲明了一個int類型的count字段——星星的數量。重新定義 Stars class 中的 toString 方法。它應該以 Intergalactic Guild of Spacewalkers 接受的格式返回星星的數量。
1000 星 - X 角色,
100顆星-Y字,
10 星 - Z 角色,
1 星 - *。幾個例子:
1001 顆星 - X*,
576 顆星 - YYYYYZZZZZZZ******,
必須使用最少的字符數。 也就是說,例如,101 顆星必須表示為 Y*,而不是 ZZZZZZZZZZ*。
我制作了一個模板,但不幸的是,我不知道如何進行所有計算。
public class Stars {
int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return Integer.toString(count);
}
public static void main(String[] args) {
Stars stars = new Stars();
stars.setCount(2253); // ZZZ***
System.out.println(stars);
System.out.println(stars.getCount());
}
}
我想創建一個數字數組 1000、100、10、1,然后計算其中有多少被使用。
不幸的是,我不知道如何將 1000 變成 XI 也不知道 2 是否在 ** 中。
請檢查我的草稿,也許你可以給我一些建議或提示。
public class Test {
public static void stars(int amount)
{
int[] number = new int[]{ 1000, 100, 10, 1 };
int[] numberCounter = new int[4];
for (int i = 0; i < 4; i++) {
if (amount >= number[i]) {
numberCounter[i] = amount / number[i];
amount = amount - numberCounter[i] * number[i];
}
}
for (int i = 0; i < 4; i++) {
if (numberCounter[i] != 0) {
System.out.print(numberCounter[i]);
}
}
}
public static void main(String argc[]){
int amount = 2253; // should be : XXYYZZZZZ***
stars(amount);
}
}
// Or maybe I can use this formula, thank you
//int units = count % 10;
//int tens = (count / 10) % 10;
//int hundreds = (count / 100) % 10;
//int thousands = (count / 100) % 10;
這會起作用:
int x = 101;
StringBuilder builder= new StringBuilder();
while (x>1000) {
builder.append("X");
x-=1000;
}
while (x<1000&&x>100) {
builder.append("Y");
x-=100;
}
while (x<100&&x>10) {
builder.append("Z");
x-=10;
}
while (x<10 && x!=0) {
builder.append("*");
x-=1;
}
System.out.println(builder.toString());
重點是只要星星的數量是在一個區間append一個字符到字符串然后減少數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.