目前我正在自学Java,我真的很想学到很多东西。我让我的程序员朋友给我一些任务,他给了我这个。
如何根据输入的数字显示星号?
示例
Enter Number:7
*
**
***
*,我已经写了一段代码,但我还是无法理解。请举几个例子好吗?
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
/*promt for input*/
System.out.println( "Enter number: " );
int how_many = input.nextInt();
for(int i = 1; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
System.out.print( "*" );
}
System.out.println("");
}
input.close();
}
}如有任何帮助或建议,将不胜感激。
发布于 2016-08-23 14:08:51
你的密码没问题。您只是缺少变量声明。可能你来自JavaScript背景。在每个变量( int、i和j)之前声明int,并尝试再次编译和执行它。
System.out.println( "Enter number: " );
int how_many = input.nextInt();
for(int i = 1; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
System.out.print( "*" );
}
System.out.println("");
}还有。我假设您将Scanner对象声明在所有内容之前
import java.util.*;
// etc, etc
Scanner input = new Scanner(System.in);我想我明白你的意思了:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println( "Enter number: " );
int how_many = input.nextInt();
outer:
for(int i = 1, count = 0; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
if(count >= how_many)
break outer;
System.out.print( "*" );
}
System.out.println("");
}
input.close();
}发布于 2016-08-23 14:20:35
class Print{
public static void main(String argas []){
Scanner in=new Scanner(System.in);
System.out.println( "Enter number: " );
int how_many = in.nextInt();
int count=0;
for(int i = 1; i <= how_many; i++ )
{
for(int j = 1; j <= i; j++ )
{ **if(count==how_many)
return;**
System.out.print( "*" );
count++;
}
System.out.println("");
}
}
}添加条件以检查*的数目是否小于输入。
发布于 2022-09-08 13:28:09
import java.util.Scanner; //program uses class Scanner
public class Print{
public static void main(String[] args){
//declare variables
int num;
int x; //outer counter
int y; //inner counter
//use Scanner to obtain input
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
num = input.nextInt();
//use for loop to generate the size of bar chart
for(x = 0; x < num; x++)
{
for(y = 0; y < num; y++)
{
System.out.print("* ");
}
System.out.println();
}
}
}https://stackoverflow.com/questions/39103296
复制相似问题