如何在java控制台中将文本与中心对齐? [英] How to align text to center in java console?

查看:187
本文介绍了如何在java控制台中将文本与中心对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在java eclipse控制台中居中对齐文本。例如,行必须是44个字符。我试过上面的代码,但我认为它不会起作用。我怎么能这样做?

我想最简单的就是在空白上拆分,然后循环遍历数组,每当行长度过宽时打印每一行后跟一个空格或换行符下一个字。处理超过行限制的单词,并将它们打印在自己的行上。



我尝试过:



How can I center align text in java eclipse console. For example line must be 44 character. I tried above code but I think it is not going to work. How can I do that?
I guess the easiest would be to split on whitespace, then looping through the array, printing each line followed by a space or a newline whenever the line length would be too wide with the next word. Take care of words that are longer than the line limit, and print them on its own line.

What I have tried:

public class printcenter {
	static final String text = "Computer science is the theory that form the basis for the design and use of computers.\n" + "It involves the study of algorithms\n"
			+ "It can be divided into a variety of theoretical and practical disciplines\n" + "Some fields are highly abstract\n\n";

	/**
	 * @param text           
	 */
	static void printCentered(String text) {
		String[] textArray=text.split("\n");
		int line = 3;
		//System.out.println(textArray[3].length());
		for(int i = 0 ; i<=line ;i++) {
		if(textArray[i].length()==44) {
			System.out.println(textArray[i]);
			
		}
		
		}
	}

	

	public static void main(String[] args) {
 	    printcenter.printCentered(text);

}

}

推荐答案

这取决于控制台屏幕的宽度是。获取字符串长度并从屏幕宽度中减去它。将结果除以2,即在文本之前添加的空格数。对于垂直居中,请使用屏幕高度和行数。
It depends on how wide the console screen is. Get the string length and subtract it from the screen width. Divide the result by 2 and that is the number of spaces to add before the text. For vertical centring use screen height and number of rows.


这篇关于如何在java控制台中将文本与中心对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆