Reputation: 177
I was asked to create a JOptionPane
program which takes as many numbers as the user wants (as a string) and sums them together.
I thought about a pseudo like this:
int Total = 0
for (int i = 0; i<=X.length();i++)
S1
which takes the number from the beginning until the first spaceS1
into a number and add it to TotalS1
from X
, and start the loop overSo, my problem is at subtracting the S1
from the X
.
My code so far:
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); }
Upvotes: 0
Views: 2173
Reputation: 1887
This is another interpretation of the method @ZouZou used, but doesn't actually break up your string, it remembers where its already looked, and works its way along the string
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);
Upvotes: 1
Reputation: 209132
Simple solution
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (String s : x.split("\\s+")){
total += Integer.parseInt(s);
}
System.out.println(total);
Edit: "can't use arrays"- then use a Scanner
to scan the String
for 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);
Upvotes: 0
Reputation: 93902
If you didn't learn arrays yet, you can implement this like that :
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);
}
Upvotes: 2