谁能告诉我输出这种模式更优雅的解决方案是什么? 我最感兴趣的是我的makeTemplate方法,但任何其他帮助将不胜感激。 这是我的代码,我希望它更具可读性:
public class Main {
public static void makeTemplate(char tab[][], int rows, int col) {
boolean increase = true;
int j = 0;
char star = '*';
for (int i = 0; i < rows; i++) {
if (increase) {
tab[i][j] = star;
if (j >= col - 1) {
increase = false;
j--;
continue;
}
j++;
} else {
tab[i][j] = star;
if (j < 0 + 1) {
increase = true;
j++;
continue;
}
j--;
}
}
}
public static void main(String[] args) {
char[][] tab = new char[30][6];
makeTemplate(tab, 30, 6);
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(tab[i][j]);
}
System.out.println();
}
}
}
答案 0 :(得分:1)
仅对makeTemplate
public static void makeTemplate(char tab[][], int rows, int col) {
boolean increase = true;
int j = 0;
char star = '*';
for (int i = 0; i < rows; i++) {
tab[i][j] = star;
if (increase) {
if (j >= col - 1) {
increase = false;
j--;
} else {
j++;
}
} else {
if (j < 1) {
increase = true;
j++;
}else {
j--;
}
}
}
}
将continue
语句替换为else
,因为continue语句与else完全相同。在if语句中使用continue表示跳过下面的j++
或j--
。因此,只有在j++
为真时才会执行j--
或if
。
我还将if(j < 0 + 1)
改为if(j < 1)
,因为0+1
= 1
在第一个tab[i][j] = star;
之前移动if
,因为它是if
和else
中的第一行 - 感谢Betlista
答案 1 :(得分:0)
优雅的java8解决方案:
IntStream.range(0, ROWS).forEach(i -> {
int cur = i % (COLS * 2);
if(cur < 6) {
IntStream.range(0, cur).forEach(f -> System.out.print(" "));
} else {
IntStream.range(0, COLS - cur % COLS).forEach(f -> System.out.print(" "));
}
System.out.println("*");
});
当然,我还没有使用makeTemplate()
方法,但就优雅和理解能力而言,这可以很好地完成工作。
答案 2 :(得分:0)
您可以使用递归
private Workbook workbook;
private HashMap<String, CellStyle> styleMap = new HashMap<>();
public CellStyle getStyle(Font font, ExcelCellAlign hAlign, ExcelCellAlign vAlign, boolean wrapText, ExcelCellBorder border, Color color, ExcelCellFormat cellFormat) {
//build unique which represents the style
String styleKey = ((font != null) ? font.toString() : "") + "_" + hAlign + "_" + vAlign + (wrapText ? "_wrapText" : "") + ((border != null) ? "_" + border.toString() : "") + "_"
+ styleKeyColor + (cellFormat != null ? "_" + cellFormat.toString() : "");
if (styleMap.containsKey(styleKey)) {
//return existing instance from map
return styleMap.get(styleKey);
} else {
//create new style from workbook
CellStyle cellStyle = workbook.createCellStyle();
// set all formattings to new cellStyle object
if (font != null) {
cellStyle.setFont(font);
}
// alignment
if (vAlign != null) {
cellStyle.setVerticalAlignment(vAlign.getAlign());
}
//... snip ...
//border
if (border != null) {
if (border.getTop() > BorderFormatting.BORDER_NONE) {
cellStyle.setBorderTop(border.getTop());
cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
}
//... snip ...
}
if (color != null) {
XSSFColor xssfColor = new XSSFColor(color);
((XSSFCellStyle)cellStyle).setFillForegroundColor(xssfColor);
}
}
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
styleMap.put(styleKey, cellStyle);
return cellStyle;
}
}