我想写一个用户给出的数字总和。如果用户说第一个数字是1而第二个数字是5,那么应该在程序“1 + 2 + 3 + 4 + 5 = 15”上写入。我管理的结束总和为“15”,但我无法打印出如“1 + 2 + 3 + 4 + 5”这样的行。请帮帮我。
import javax.swing.JOptionPane;
public class Oppgave2{
public static void main(String[] args){
int x;
int y;
String i, j;
i = JOptionPane.showInputDialog("Write begining number:");
x = Integer.parseInt(i);
j = JOptionPane.showInputDialog("Write end number:");
y = Integer.parseInt(j);
if ( x > y || x == y){
i = JOptionPane.showInputDialog("Wrong!
Begining number is bigger or same as end number!
\nTry again! Write begining number:");
x = Integer.parseInt(i);
j = JOptionPane.showInputDialog("Write end number:");
y = Integer.parseInt(j);
}
int number;
number = x;
int sum = 0;
while(number <= y){
sum = sum + number;
number++;
}
// Here or in while it should write OptionPane.showMessageDialog(null, "1+2+3+4+5 " + sum);
JOptionPane.showMessageDialog(null, "the sum is: " + sum);
}
}
答案 0 :(得分:0)
创建一个字符串并像这样添加:
int number;
number = x;
int sum = 0;
//Message used for the sum, in the form of "1+2+3+4..."
String sumMessage = "";
while(number <= y){
//Append the number and then "+" to sumMessage.
sumMessage = sumMessage + number + "+";
sum = sum + number;
number++;
}
//Remove the final + in the sumMessage using substring.
sumMessage = sumMessage.substring(0, sumMessage.length() - 1);
// Here or in while it should write OptionPane.showMessageDialog(null, "1+2+3+4+5 " + sum);
JOptionPane.showMessageDialog(null, sumMessage + " is: " + sum);