我试图在java中打印下面的模式
***1***
**2*2**
*3*3*3*
4*4*4*4
像这样
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
//Printing the number of rows
for (int i = 1; i <= m; i++) {
//printing number of columns
for (int j = n; j > 0; j--) {
//Printing values in the pattern
for (int k = 0; k < j; k++) {
if (k == j / 2)
System.out.print(i);
}
System.out.print("*");
}
System.out.print("\n");
}
}
}
我在找到打印每行中的值的位置的逻辑上面临问题。它在我之前的采访中被问过。
答案 0 :(得分:3)
当星号(*
)替换为数字时,尝试找出公式。
如果你注意到我上面提到的两个依赖关系,公式很简单。
答案 1 :(得分:0)
我们可以根据输出编写逻辑。现在你传递值row = 4和column = 7。为此你提供了输出。基于我编写的这个程序,输出与之匹配,我们也可以修改/调整这个程序:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
int m, n;
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of rows");
m = s.nextInt();
System.out.println("Enter the no of columns");
n = s.nextInt();
s.close();
String[][] str = new String[m][n];
int frontPos = 0;
int backPos = n-1;
for (int i=0; i<m; i++){
int l = Math.round((n)/(i+2));
if(i==(m-1)){
frontPos = 0;
backPos = n-1;
} else {
frontPos = l;
backPos = n-1-l;
}
//System.out.println("Difference =="+frontPos);
boolean contFlag = false;
do{
//System.out.println("frontPos=="+frontPos+"|backPos=="+backPos);
if(frontPos == backPos){
str[i][frontPos] = new Integer(i+1).toString();
} else if(frontPos < backPos){
str[i][frontPos] = new Integer(i+1).toString();
str[i][backPos] = new Integer(i+1).toString();
}
if((backPos-frontPos) > l){
contFlag = true;
frontPos = frontPos + (l+1);
backPos = backPos -(l+1);
} else {
contFlag = false;
}
} while(contFlag);
//System.out.print("\n");
}
for(int a=0; a<m; a++){
for(int b=0; b<n; b++){
if(str[a][b]==null){
System.out.print("*");
} else {
System.out.print(str[a][b]);
}
}
System.out.print("\n");
}
}
}