[英]Subtracting strings
我被要求創建一個JOptionPane
程序,該程序采用用戶想要的數字(作為字符串)並將它們加在一起。 我想到了這樣的偽:
int Total = 0
for (int i = 0; i<=X.length();i++)
S1
,該字符串從開始到第一個空格都采用數字 S1
轉換為數字並將其添加到總計 X
減去S1
,然后開始循環 所以,我的問題是從X
減去S1
。
到目前為止,我的代碼:
public static void main(String[] args) {
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (int i = 0; i<=x.length();i++){
String s1 = x.substring (0, x.indexOf(' '));
total += Integer.parseInt(s1);
x = x - s1;
}
JOptionPane.showMessageDialog(null, "the sum is" + total); }
如果您還沒有學習數組,則可以這樣實現:
public static void main(String[] args){
int total = 0;
String x = "12 7";
String s1 = x.trim(); //trim the string
while(!s1.isEmpty()){ //loop until s1 is not empty
int index = x.indexOf(' ');//search the index for a whitespace
if(index != -1){ //we found a whitespace in the String !
s1 = s1.substring(0, index); //substract the right number
total += Integer.parseInt(s1);
x = x.substring(index+1).trim(); //update the String x by erasing the number we just added to total
s1 = x; //update s1
} else {
total += Integer.parseInt(s1); //when there is only one integer left in the String
break; //break the loop this is over
}
}
System.out.println(total);
}
這是@ZouZou使用的方法的另一種解釋,但實際上並沒有分解您的字符串,它會記住它已經被查找的位置,並沿着該字符串工作
int total = 0;
String inputString = "12 7 8 9 52";
int prevIndex = 0;
int index = 0;
while (index > -1) {
index = inputString.indexOf(' ', prevIndex);
if (index > -1) {
total += Integer.parseInt(inputString.substring(prevIndex, index));
prevIndex = index + 1;
} else {
total += Integer.parseInt(inputString.substring(inputString.lastIndexOf(' ')+1));
break;
}
}
System.out.println(total);
簡單的解決方案
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (String s : x.split("\\s+")){
total += Integer.parseInt(s);
}
System.out.println(total);
編輯: “不能使用數組” -然后使用Scanner
掃描String
的nextInt()
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
Scanner scanner = new Scanner(x); // use scanner to scan the line for nextInt()
while (scanner.hasNext()){
total += scanner.nextInt();
}
System.out.println(total);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.