[英]How do I make this output happen in java?
I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure. 我是一个初学者,我想使用for循环和下标输出以下内容,但不确定。
output: 输出:
Jamaica
amaica
maica
aica
ica
ca
a
What can I do, in order to achieve this output? 为了实现此输出,我该怎么办?
First: You need to loop for generating n
line which is the length of array. 第一:您需要循环生成n
行,这是数组的长度。
Second: You need to print the spaces with is same value as row - 1
number of times. 第二:您需要打印与row - 1
相同的空格row - 1
次。
Second: You need to print character start from row - 1
number to the length of the string. 第二:您需要从row - 1
开始打印字符row - 1
数字到字符串的长度。
And the final solution will be: 最终的解决方案将是:
public class MyClass {
public static void printStr(String str) {
int i,j;
for (i = 0; i < str.length();i++) {
for(j = 0; j < i; j++) {
System.out.print(" ");
}
for(j = i; j < str.length();j++) {
System.out.print(str.charAt(j));
}
System.out.println("");
}
}
public static void main(String args[]) {
MyClass.printStr("Jamaica");
}
}
I would use two regular expressions , the first to terminate the loop when the String
is filled with white space. 我将使用两个正则表达式 ,第一个在String
充满空白时终止循环。 The second to replace the first non-white space character with a white space in the loop body (after printing the current String
value). 第二个将循环正文中的第一个非空白字符替换为空白(在打印当前String
值之后)。 And, if it's possible the String
might be empty you should guard against that. 并且,如果String
可能为空,则应注意这一点。 Like, 喜欢,
String s = "Jamaica";
if (!s.isEmpty()) {
while (!s.matches("\\s+")) {
System.out.println(s);
s = s.replaceFirst("\\S", " ");
}
}
Outputs (as requested) 输出(根据要求)
Jamaica
amaica
maica
aica
ica
ca
a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next(); //input through scanner class
int len = s.length();
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
System.out.print(" ");
}
for(int j=i;j<len;j++){
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
Hopefully that helps 希望有帮助
Try following code: 尝试以下代码:
StringBuilder country = new StringBuilder("Jamaica");
for(int i=0; i< country.length();i++){
if(i > 0)
{
for(int j=0;j<i;j++){
country.setCharAt(j,' ');
}
}
System.out.println(country);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.