我需要的是对我的代码进行一些修改,以便我的空心钻石的每一部分都印有一个字母" HURRICANE"
我的代码是:
String st1="HURRICANE";
int a = 0;
for(int i = 5;i >= 1;i--){
for(int j = 1;j <= 9;j++){
if(j == i || (10 - i) == j)
{
System.out.print(st1.charAt(a)); \\needs change
}
else {
System.out.print(' ');
}
}
System.out.println();
}
for(int i =2;i <= 5;i++){
for(int j = 1;j <= 9;j++){
if(j == i || (10 - i) == j){
System.out.print(st1.charAt(a)); \\needs change
}
else
{
System.out.print(' ');
}
}
System.out.println();
}
输出结果如下:
H
H H
H H
H H
H H
H H
H H
H H
H
我需要修改我的&#34; charAt&#34;声明一点,所以它出来了:
H
U U
R R
R R
I I
C C
A A
N N
E
我该如何制作我的印刷声明?
答案 0 :(得分:1)
值得注意的是,提供的示例仅适用于与“HURRICANE”相同长度的字符串。优秀的解决方案适用于所有字符串。
部分解决方案供您完成,因为我认为这是您的课程,我不希望您复制/粘贴/失败考试:P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i) + st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
答案 1 :(得分:0)
String st1="HURRICANE";
int a = 0;
for(int i = 5;i >= 1;i--){
for(int j = 1;j <= 9;j++){
if(j == i || (10 - i) == j)
{
System.out.print(st1.charAt(5-i));
}
else {
System.out.print(' ');
}
}
System.out.println();
}
for(int i =2;i <= 5;i++){
for(int j = 1;j <= 9;j++){
if(j == i || (10 - i) == j){
System.out.print(st1.charAt(3+i));
}
else
{
System.out.print(' ');
}
}
System.out.println();
}
答案 2 :(得分:0)
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
答案 3 :(得分:0)
假设一个单词有奇数个字符,否则我们会得到一个弯曲的菱形。
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
输出:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a