英文:
How to implements pattern for below logic?
问题
我尝试了以下代码
public static void rightTriangle(int n) {
int rows, i, j=0;
String s = "从纽约到英国的廉价航班";
String[] arr = s.split("\s");
for (i = 0; i <= arr.length - 1; i++) {
for (j = 0; j <= i; j++)
System.out.print(arr[j] + " ");
System.out.println("");
}
}
我得到了以下输出
<pre>
从纽约到英国的廉价航班
从纽约到英国的廉价航班
从纽约到英国的廉价航班
从纽约到英国的廉价航班
从纽约到英国的廉价航班
从纽约到英国的廉价航班
从纽约到英国的廉价航班
</pre>
<pre>
我
我是
我是一个
我是一个女孩
是
是一个
是一个女孩
一个
一个女孩
女孩
</pre>
英文:
I tried with
public static void rightTriangle(int n) {
int rows, i, j=0;
String s = "Cheap flights from New York to United Kingdom";
String[] arr = s.split("\\s");
for (i = 0; i <= arr.length - 1; i++) {
for (j = 0; j <= i; j++)
System.out.print(arr[j] + " ");
System.out.println("");
}
}
And I got
<pre>
Cheap
Cheap flights
Cheap flights from
Cheap flights from New
Cheap flights from New York
Cheap flights from New York to
Cheap flights from New York to United
Cheap flights from New York to United Kingdom
</pre>
<pre>
I
I am
I am a
I am a girl
am
am a
am a girl
a
a girl
girl
</pre>
答案1
得分: 2
这里您需要再引入一个 for 循环以获得您所需的输出。
String s = "纽约到英国的廉价航班";
String[] arr = s.split("\\s");
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
for (int k = i; k <= j; k++) {
System.out.print(arr[k] + " ");
}
System.out.println("");
}
System.out.println("");
}
英文:
Here you need to introduce one more for loop to get your desired output.
String s = "Cheap flights from New York to United Kingdom";
String[] arr = s.split("\\s");
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length; j++)
{
for (int k = i; k <= j; k++)
{
System.out.print(arr[k] + " ");
}
System.out.println("");
}
System.out.println("");
}
答案2
得分: 1
public class Main {
public static void main(String[] args) {
rightTriangle(3);
}
public static void rightTriangle(int n) {
String s = "纽约飞往英国的廉价航班";
String[] arr = s.split("\\s");
for (int k = 0; k < arr.length - n; k++) {
for (int i = k; i < arr.length; i++) {
for (int j = k; j <= i; j++)
System.out.print(arr[j] + " ");
System.out.println();
}
System.out.println();
}
}
}
英文:
public class Main {
public static void main(String[] args) {
rightTriangle(3);
}
public static void rightTriangle(int n) {
String s = "Cheap flights from New York to United Kingdom";
String[] arr = s.split("\\s");
for(int k = 0;k<arr.length-n;k++) {
for (int i = k; i< arr.length; i++) {
for (int j = k; j <= i; j++)
System.out.print(arr[j] + " ");
System.out.println();
}
System.out.println();
}
}
}
this should produce the correct output, you could tweak it to put it in a method yourself if needed however this should work fine. You can dictate how many triangles are displayed by changing the rightTriangle(int n)
parameter, so if you put 0 in the method call it will draw all the triangles and if you put 8 it wont draw any because there are 8 words.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论