尝试使用Java打印半金字塔格式的字母XXYY时遇到问题。这是用户输入7的高度时的预期输出:
XX
YYXX
XXYYXX
YYXXYYXX
XXYYXXYYXX
YYXXYYXXYYXX
XXYYXXYYXXYYXX
这是我的代码:
public static void main(String[] args){
int height = 0;
String display = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
height = sc.nextInt();
for(int i = 1; i <= height; i++){
for(int j = 1; j <= i; j++){
if(j %2 == 0){
display = "YY" + display;
}else{
if(j == 1){
display = "XX";
}
}
System.out.print(display);
}
System.out.println();
}
}
我的逻辑是什么,我想先检查偶数/奇数行,然后将XX或YY添加到显示字符串。首先,我检查第一行,然后将XX添加到显示字符串。然后,如果是偶数行,我将YY附加到显示字符串的前面。
但我的问题是我不知道如何计算每一行的XX和YY数量。这是我的输出:
XX
XXYYXX
XXYYXXYYXX
XXYYXXYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXXYYYYYYXX
答案 0 :(得分:1)
(function() {
'use strict';
function config($routeProvider) {
$routeProvider
.when('/createProduct', {
templateUrl: 'app/components/createProduct/createProductView.html',
controller: 'createProductCtrlr'
});
}
function createProductCtrlr($scope, $rootScope, $location) {
$scope.platformSel = '';
$scope.tileSelect = function(target) {
console.log(target + " selected");
};
}
angular
.module('pacman')
.controller('createProductCtrlr', ['$scope', '$rootScope', '$location', createProductCtrlr])
.config(['$routeProvider', config]);
})();
答案 1 :(得分:1)
这应该这样做:
public static void main (String[] args) throws java.lang.Exception
{
int ht = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
ht = sc.nextInt();
String text = "";
for(int i=0; i<ht; i++)
{
if (i%2!=0)
text = "YY" + text;
else
text = "XX" + text;
System.out.println(text);
}
}
也适用于单for
循环!