我想打印一个类似的模式:
到目前为止,我只能实现奇数这样的数字:
1
3 5 7
-
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
我是初学者和新学员。请帮忙
答案 0 :(得分:1)
我不确定预期的结果是什么,因为该模式不明确,但这可能是您正在寻找的:
Tags
结果:
int evenCounter = 1;
int oddCounter = 2;
for (int i = 1; i <= 10; i++) {
boolean even = (i % 2 == 0);
for (int j = 1; j < i; j++) {
System.out.print((even ? evenCounter : oddCounter) + " ");
evenCounter += even ? 2 : 0;
oddCounter += even ? 0 : 2;
}
System.out.println();
}
如果每行的长度很重要,那么第二个for循环应该有一个不同的退出条件,我想
答案 1 :(得分:0)
要从3 5 7获取模式,此代码可以执行,其中MAX_PATTERN_NUM
是模式最后一行的第一个数字(在您的示例中为MAX_PATTERN_NUM = 15
)
for(int i = 3; i <= MAX_PATTERN_NUM ; i+=3)
for(int j = i; j <= (i + 4); j+=2)
System.out.print(j + " ");
System.out.println();
但是,我看不到使用相同的嵌套for循环获取整个模式的逻辑方法,所以我希望这有帮助
答案 2 :(得分:0)
这个怎么样:
public void printPattern(){
int evenCounter = 2;
int oddCounter = 1; //counters
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt(); //input
}
for(int i = 1; i <= num ; ++i){
if(i % 2 == 0)
evenCounter = addNumbers(i, evenCounter); //print line with evenCounter
else
oddCounter = addNumbers(i, oddCounter); //print line with oddCounter
}
}
private int addNumbers(int i, int counter){
for(int j = 0; j < i;){
if(getIntLength(counter) + j > i) //if the number to long
System.out.print(cut(counter, getIntLength(counter) + j - i) + " "); //output the cut version
else
System.out.print(counter + " ");
j += getIntLength(counter);
counter += 2;
}
System.out.println();
return counter;
}
private String cut(int i, int length){
return Integer.toString(i).substring(0,length); //get substring of int
}
private int getIntLength(int i){
return Integer.toString(i).length(); //get the length of int value
}
这不是那么简单,但我没有看到更简单的方法
我的回答是基于假设最后2是截止21
答案 3 :(得分:-1)
int n,i,j,o=1,e=2;
System.out.println("enter n:");
n=sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
if(i%2!=0){
System.out.print(o);
o+=2;
}
if(i%2==0){
System.out.print(e);
e+=2;
}
}
System.out.println();
}