Java-在while循环中存储值
我是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 ****
这就是答案:
import java.util.Scanner;
public class Histogram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// Constant
final String CH = "*";
int count = 0;
int number = 0;
int start = 1;
int width = 0;
int line = 0;
String output = "";
String store="";
// 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 ;
store+=output;
}
width = 0;
}
}
System.out.print(store);
}
}
输出是连续的星星,但我希望每个星星都在不同的行上,所以我将商店+ =输出更改为存储+ =输出+“\ n”,但每个星星都会变成另一个星星,我该怎么办? –
因此,好的我发现答案非常感谢您的帮助 –
使用列表,例如ArrayList,而不是Array,因为大小可以动态增长。
例如,
List<Integer> ints = new ArrayList<>();
ints.add(5);
ints.add(2);
ints.add(7);
for(Integer i : ints){
System.out.println(i);
}
如果你不想重复,你可以使用一个设置来代替。
你只需要创建而范围以外的变量(像String
或StringBuilder
(首选))和而不是直接打印你的结果,你会追加无论是输出,这个变量并打印最后。
使用这种方法,基本上是收集整个输出并一次打印出来。
...
//create a output variable outside while loop. You can also use simple String
StringBuilder out = new StringBuilder();
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 ;
//instead of directly printing, you can append your output to out variable.
out.append(output);
}
width = 0;
}
}
//after coming out of the loop, you can now print it
System.out.print(out);
...
在 “其他” 你可以只存储数字输入:
List<Integer> myList = new ArrayList<>(); //previously defined
(...)
else {
myList.add(number);
}
,然后while循环外,一旦填写您的ArrayList:
for(int i=0;i<myList.size();i++)
{
for(int j=0;j<myList.get(i);j++)
{
System.out.print("*");
}
System.out.print("\n");
}
如果你想,你可以创建一个字符串变量保存所有行。你可以只追加输出+“\ n”,让你的端线会是什么样 输出1 输出2 OUTPUT3等 – chatton
只是如果事情会在一起,然后(不是人)单独使用它们,请使用数组或列表以存储您的数据 –
是否要在不同行中打印每次迭代的输出? – bane19