我希望代码执行此操作: 如果我输入' 5'它将打印5个三角形行,如下所示:
+
++
+++
++++
+++++
之后我也想反过来看它是这样的:
+++++
++++
+++
++
+
这是我的尝试:
package test;
import java.util.Scanner;
public class Testo1
{
public static void main(String[] args)
{
//
Scanner input = new Scanner(System.in);
int Rows = 0;
//
while(Rows<=0){
System.out.print("How many rows do you want in your triangle, more than 0?: ");
Rows = input.nextInt();
}while(Rows>=0){
//Honestly, I don't know what to do here or the logic to implement.
}
}
}
我评论了我迷路的while循环部分。我希望这在一个while循环嵌套中。有人可以指导我吗?
答案 0 :(得分:0)
是的,你必须使用嵌套循环。
看看这段代码:
$(document).ready(function() {
$(function(){
var current = window.location.href;
$('#wa li').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.find('a').attr('href')) !== -1){
$this.addClass('active');
}
})
})
});
对于反向,您只需将循环更改为:
Scanner input = new Scanner(System.in);
int Rows = 0;
while (Rows <= 0) { // Keep asking the user if they enter something less than zero
System.out.print("How many rows do you want in your triangle, more than 0?: ");
Rows = input.nextInt();
}
// If you got out of the while loop, that means you got a positive row number
for (int i = 1; i <= Rows; i++) { // number of lines
for (int j = 1; j <= i; j++) // number of stars at each line
System.out.print("*"); // printing stars
System.out.print("\n"); // line break
}
答案 1 :(得分:0)
您可以通过循环和聚焦来实现任何模式 他们如何实际工作和打印。给出正常三角形打印的示例: -
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((i+j)>n)
{
System.out.print("#");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
The output would be:-
#
##
###
####
#####
同样,您可以进行更改并生成不同的输出。例如,使用空字符串更改#,您将获得逆转顺序。
#####
####
###
##
#
你可以做的另一种模式是: -
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
for(int i = 0; i < n; i++){
for(int j=i+1;j>0;j--){
System.out.print("*");
}
System.out.println();
}
This will output as:-
*
**
***
****
*****
我希望这会有所帮助。