![](/img/trans.png)
[英]How can I calculate the difference between two times in 24h format using Java?
[英]How can I calculate the difference of chars between two strings and make them equal in Java?
我在學校開始使用Java,但在這個練習中遇到了麻煩。 我有兩個數字,我必須找出這兩個字符之間的字符差,並使字符數相等,我必須添加多個零作為缺失的字符。 因此,例如,如果我有10和100,則輸出將為010和100。我想在理解如何方面有所幫助,有了這兩個數字的string.length,我可以檢測到缺失的字符並加0。
import java.util.Scanner;
public class exercise {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter n1");
System.out.println("Enter n2");
String n1 = myObj.nextLine();
String n2 = myObj.nextLine();
System.out.println("n1 is: " + n1);
System.out.println("n2 is: " + n2);
System.out.println("length n1: "+ n1.length());
System.out.println("length n2: "+ n2.length());
}
}
我不會為您提供解決方案代碼,但會為您提供有關帶有上下文的String.length方法的信息。
假設您有兩個字符串變量:
n1 = "18214120"
n2 = "100"
n1.length()將產生8,n2.length()將產生3。利用此信息,您知道n1是包含更多字符的數字,並且您希望n2填充0直到n2.length()= n1 .length(),您要在n2的左邊添加幾個零?
那么要填充的零的數量必須等於:
n1.length()-n2.length()
8-3 = 5。
因此,在n2的左邊加上5 0將使它成為00000100,我相信這是您想要的。
得到丟失的字符
int charsMissing = n1.length() - n2.length();
添加額外的零作為丟失的次數。
if (charsMissing > 0) // check if there actually are missing in {
for (int i = 0; i < charsMissing; i++) {
n1 = "0" + n1
}
}
重要的是要知道在更改String對象時,可以使用+
運算符將兩個字符串連接在一起。 例如:
String s1 = "hello";
String s2 = "world";
String combined = s1 + s2;
System.out.println(combined);
這將輸出:
helloworld
如果要在字符串前面加上數字0,則可以使用以下代碼:
String zeroAdded = "0" + someString;
由於您不想為添加的每個零創建新的字符串,因此Java允許您串聯一個字符串並將結果分配給它自己。 上面的示例也可以寫成:
String someString = "0" + someString; //The value of someString will be overwritten with the result of the concatenation.
現在您所要做的就是重復此步驟X次,即Xs的長度差。 可以使用for循環或while循環。 選擇哪個是一個完整的主題,我建議使用谷歌搜索這些術語以獲取示例和比較。 對於這些類型的練習,盡管性能或可讀性之間的差異可以忽略不計。 這是一個for循環的示例:
int difference = Math.abs(n1.length() - n2.length()) //Taking absolute value, because we don't know which string was the longest.
for(int i = 0; i < difference; i++){
if(n1.length() > n2.length()){ //n1 is longer, so prepend the 0 to n2
n2 = "0" + n2;
}
if(n1.length() < n2.length()){ //n2 is longer, so prepend the 0 to n1
n1 = "0" + n1;
}
}
System.out.println("n1 is now: " + n1);
System.out.println("n2 is now: " + n2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.