计算1+2+3+…+100的和(提示利用while语句)
public class test{
public static void main(String[] args) {
int x=1;
int sum=0;
while (x<=100){
sum+=x;
x++;
}
System.out.println(sum);
}
}
计算从1到100的所有奇数相加(提示利用while语句)
用do while 循环来改写1加到100
public class test {
public static void main(String[] args) {
int x=1;
int sum=0;
while (x<101){
if (x%2!=0){
sum=sum+x;
}
x++;
}
System.out.println(sum);
}
}
编写一个简单程序,要求数组长度为5,分别赋值10,20,30,40,50,在控制台输出该数组的值。(知识点:数组定义和创建、一维数组初始化)
public class test {
public static void main(String[] args) {
int[] arr=new int[]{10,20,30,40,50};
for (int i=0;i< arr.length;i++){
System.out.println(arr[i]+" ");
}
}
}
将一个字符数组的值(neusofteducation)拷贝到另一个字符数组中.(知识点:数组复制)
public class test {
public static void main(String[] args) {
char x[]={'n','e','u','s','o','f','t','e','d','u','c',
'a','t','i','o','n'};
char y[]={};
y=x;
System.out.println(y);
}
}
给定一个有9个整数(1,6,2,3,9,4,5,7,8)的数组,先排序,然后输出排序后的数组的值。(知识点:Arrays.sort排序、冒泡排序)
public class test {
public static void main(String[] args) {
int[] arr=new int[]{1,6,2,3,9,4,5,7,8};
Arrays.sort(arr);//java提供排序组合
for (int n:arr){
System.out.print(n+" ");
}
}
}
在一个有8个整数(18,25,7,36,13,2,89,63)的数组中找出其中最大的数及其下标。(知识点:数组遍历、数组元素访问)
public class test {
public static void main(String[] args) {
int[] a = {18,25,7,36,13,2,89,63};
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length); //注意:System.arraycopy(),不要漏了System.
for(int y=0; y<b.length-1; y++) {
if(b[y]>b[y+1]) {
int temp = b[y];
b[y] = b[y+1];
b[y+1] = temp;
}
}
for(int element : b) {
System.out.print(element + " ");
}
System.out.print("这个数组最大的数是:"+ b[b.length-1]);
int xiabiao = 0;
for(int i=0; i<a.length; i++) {
if(a[i]==b[b.length-1]) {
xiabiao = i;
}
}
System.out.print("下标为:"+xiabiao);
}
}