gpt4 book ai didi

Java 在 while 循环中存储值

转载 作者:行者123 更新时间:2023-11-29 09:28:08 26 4
gpt4 key购买 nike

我是 Java 初学者,我有一项关于循环的作业。我知道这个问题对您来说可能听起来很基础,但我找不到可以理解的答案。我的代码基本上是这样的;

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;


}
}

}
}

这运行完美,但在每次用户输入后都会打印星星的输出。我想存储每个循环的输出,并在输入负整数时在最后一起打印它们。如何存储我不知道用户将输入多少输出的输出?简而言之,我想要以下输出

Enter the numbers : 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);

}
}

关于Java 在 while 循环中存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40486594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com