我怎样才能创建一个循环来创建一个空格,这样我就可以输出更多的空格而不是更少的空格。输入的字符串应该以星号为中心。我无法弄清楚如何让for循环来做到这一点。所以,如果你能帮我找出原因或修复我的代码那么棒。
/*
*******
* *
* I *
* *
*******
instead of
***
* *
*I*
* *
* /
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter a string: ");
String word = keyboard.nextLine();
int len=word.length();
for(int i=0;i<len+2;i++)
{
System.out.print("*");
}
System.out.println();
System.out.print("*");
for(int i=0;i<len;i++) //adjust the number of tabs
{
System.out.print(" ");
}
System.out.print("*");
System.out.println();
System.out.println("*"+word+"*");
System.out.print("*");
for(int i=0;i<len;i++) // adjust the number of tabs
{
System.out.print(" ");
}
System.out.print("*");
System.out.println();
for(int i=0;i<len+2;i++)
{
System.out.print("*");
}
}
答案 0 :(得分:1)
我不确定您是只想要水平间距还是水平和垂直间距
如果你只想要水平间距,那么你可以使用下面的
你可以扩展它以获得垂直间距
答案 1 :(得分:1)
import java.util.Scanner;
import static java.lang.System.out;
public class SomeClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
out.print("Enter a string: ");
String word = input.nextLine();
input.close();
out.print("\n\n");
// First find out how many wide the first border should be
int top = word.length() + 4/*spaces */ + 2/*asterisks */ ;
// Print out that many asterisks
while(top != 0) out.printf("*", top--);
// Print out the second line, which is the length of top, except only
// the first and last character are asterisks.
out.printf("\n* %" + word.length() + "s *\n", " ");
// Print out the word
out.printf("* %s *", word);
out.printf("\n* %" + word.length() + "s *\n", " ");
int bot = word.length() + 6;
while(bot != 0) out.printf("*", bot--);
}
}
控制台输出:
Enter a string: STACK OVERFLOOOWWWW
*************************
* *
* STACK OVERFLOOOWWWW *
* *
*************************
答案 2 :(得分:0)
我设法使用静态方法和一些循环来解决问题。希望它可以帮助您满足您的需求。无论字符串长度如何,它都应该看起来正确。
public class SO5 {
public static void main(String[] args) {
String st = "Photograph"; //String
int length = st.length() + 4; //Length of string plus 4, for star and space at front and back
for(int i = 0; i < 9; i++){//Number of levels needed
if(i == 0 || i == 8){//Start or end
printForLength("*", length); //Print relevant number of start
System.out.println(); //Next line
} else if(i % 2 == 0){ //If an even number
if(i == 4){ //If the middle
System.out.println("* " + st + " *"); //Print star our string plus star
} else { //If not middle
System.out.print("*"); //Star
printForLength(" ", length - 2); //spaces for length of string -2 for start and end stars
System.out.print("*");//End star
System.out.println();//New line
}
}
}
}
//Method prints a character for a set number of times
public static void printForLength(String s, int length){
for(int j = 0; j < length; j++){
System.out.print(s);
}
}
}
祝你好运!