双重for 例题
双重for
任务1:
public static void main(String[] args) {
int a = 7;
if (a%2==0) {
a++;
}
for (int i = 1; i <=(a/2); i++) {
for (int j = a-i; j >0; j--) {
System.out.print(" ");
}
for (int j = (2*i)-1; j >0; j--) {
System.out.print("*");
}
System.out.println();
}
for (int i = a-(a/2); i >0; i--) {
for (int j = a-i; j > 0; j--) {
System.out.print(" ");
}
for (int j = (2*i)-1; j >0; j--) {
System.out.print("*");
}
System.out.println();
}
}
任务2:
public static void main(String[] args) {
int n=7;
int s=n/2+1;
for(int i=1;i<=s;i++){
for(int j=1;j<=s-i;j++){
System.out.print(" ");
}
for(int k=1;k<=2*i-1;k++){
if(k==1||k==2*i-1){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
for(int u=1;u<=s-1;u++){
for(int m=1;m<=u;m++){
System.out.print(" ");
}
for(int o=1;o<=n-2*u;o++){
if(o==1||o==n-2*u){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
选做:
顾客去5家商场购物,每家商场限购3样商品,离开每家商场时结算,最后5家购物完 计算总消费金额。
public class shangcahng5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0,n;
for(int i=1;i<=5;i++){
System.out.println("欢迎光临第"+i+"商场");
for(int j=1;j<=3;j++){
System.out.println("请输入购的第"+j+"件商品的金额:");
Scanner input=new Scanner(System.in);
n=input.nextInt();
sum=sum+n;
System.out.println("离开第"+i+"商场时共消费:"+sum);
}
}
}