1.数组和循环的使用
int b[][] = {{1,2,3}, {4, 5},{6, 7}};
int sum = 0;
for(int i = 0; i<b.length; i++)
{
for(int j = 0 ; j < b[i].length; j++)
{
sum += b[i][j];
}
}
System.out.println("Sum = " + sum)
结果是:28看不懂啊,能稍微给解释一下吗???
2.编写程序,按字母表顺序和逆序每隔一个字母打印,即打印出:a c e g i k m o q s u w y z x v t r p n l j f d b
3.编写程序,从键盘输入一个4位数(数值),求出各位数字之和。
------解决方案--------------------
- Java code
int b[][] = {{1,2,3}, {4, 5},{6, 7}}; int sum = 0; for(int i = 0; i<b.length; i++)//i=0 这是b[0]就是 {1,2,3} 数组里面第1个数组 { for(int j = 0 ; j < b[i].length; j++) //这里就是遍历上面得到这个数组 { sum += b[i][j]; } } //这段代码就是把所有的数相加
------解决方案--------------------
给人以鱼不如授人以渔。
第一题修改如下:
- Java code
int b[][] = { { 1, 2, 3 }, { 4, 5 }, { 6, 7 } }; int sum = 0; for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i].length; j++) { System.out.println(i+" "+j+" "+b[i][j]); sum += b[i][j]; } } System.out.println(sum);
------解决方案--------------------
------解决方案--------------------
2,
- Java code
public class AnswerDemo01{ public static void main(String[] args) { String str="abcdefghijklmnopqrstuvwxyz"; char[] cr=new char[str.length()]; char[] cr1=new char[str.length()]; for(int i=0;i<str.length();i++) { if(i%2!=0) continue; cr[i]=str.charAt(i); } System.out.println(new String(cr)); int j=0; for(int i=str.length()-1;i>=0;i--) { if(i%2!=0) continue; cr1[j]=str.charAt(i); j++; } for(char c:cr1) System.out.print(c+" "); }}