我是Java的初学者,我在循环中有一个任务。我知道这个问题听起来很基本,但我找不到一个可以理解的答案。我的代码基本上看起来像;Java-在while循环中存储值
import java.util.Scanner;
public class Histogram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// Constant
final String CH = "*";
// Variables
int number;
int count;
int start;
int width;
int line;
String output;
// Program Code
count = 0;
number = 0;
start = 1;
width = 0;
line = 0;
output = "";
// Creating the loop
while (start == 1)
{
System.out.println("Enter the numbers");
number = scan.nextInt();
if (number < 0)
{
start = 0;
}
else
{
while (width < number)
{
output = CH + " " ;
width = width + 1 ;
System.out.print(output);
}
width = 0;
}
}
}
}
这可以很好地运行,但在每个用户输入之后会打印恒星的输出。我想存储每个循环的输出,并在输入负整数时将它们一起打印。如何储存输出,我不知道用户输入了多少个输出? 总之我想有以下输出
输入数字:3 5 6 4 -1 //号码的用户输入
3 *** 5 ***** 6 *** *** 4 ****
如果你想,你可以创建一个字符串变量保存所有行。你可以只追加输出+“\ n”,让你的端线会是什么样 输出1 输出2 OUTPUT3等 – chatton
只是如果事情会在一起,然后(不是人)单独使用它们,请使用数组或列表以存储您的数据 –
是否要在不同行中打印每次迭代的输出? – bane19