1. 程式人生 > >java循環、數組練習

java循環、數組練習

nextline import 大於 static system.in for 一個數 next 生成

   System.out.println("請輸入學生個數");
	int a=sc.nextInt();//定義一個變量說明學生的數量
	int max=0;
   int[] scores= new int[a];//定義一個數組來接收獲取的學生的成績
   for( int i=0; i<scores.length; i++){//依次從鍵盤獲取a個學生的成績,並賦給相應的數組元素
   int b=sc.nextInt();
   scores[i]=b;
   if(scores[i]>max){
       max=scores[i];}}


	   //遍歷學生成績數組,並根據學生成績與最高分的差值,賦予相應的等級,並輸出
   System.out.println(max);
   char level;
   for( int i=0;i<scores.length;i++){
       if(scores[i]>max-10){
	      level=‘A‘;}
	   else if(scores[i]>max-20){
	      level=‘b‘;}
	    else if(scores[i]>max-30){
	      level=‘c‘;}
		 else{
		   level=‘d‘;}
		   System.out.println("student"+i+"的成績"+level);}
   }
}

  先讀入學生人數,再根據學生人數創建學生成績int數組

技術分享

//依次輸入幾個數,當輸入0的時候停止,並計算出大於0或者小於0的數各有多少個

import java.util.Scanner;
class lianxi{
public static void main(String[] args)
{ Scanner sc=new Scanner(System.in);
System.out.println("qingshuruyigeshu ");

int a=0;
int z=0;
for( ; ; ){
int b=sc.nextInt();//獲取輸入值得語句要寫在循環內,每次循環獲取一次數值
if(b>0){
a++;}
else if(b<0){
z++;}
else{
break;
}

}

System.out.println("大於0的"+a);
System.out.println("小於0的"+z);
sc.close();
}
}

技術分享

//輸入學生成績,並且在輸入exit的時候停止。
import java.util.Scanner; public class chengji{ public static void main(String[]args){ Scanner s=new Scanner(System.in);//System.in輸入 while(true) {System.out.println("qingshuruchengji") ; //實例化對象。 String str =s.nextLine(); //這裏的s.nextline是對象.nextline方法。 這句話的意思是獲取輸入的數據。 if(str.equals("exit")){ break;} int a=Integer.parseInt(str); if(a>90){ System.out.println("您的成績的S") ; }else if(a>80){ System.out.println("您的成績是A"); }else if(a>70){ System.out.println("您的成績是B"); }else if(a>60){ System.out.println("您的成績是c"); } /*else if(a<0){ break;}*/ }}}

  註意判斷string==某個字符串的時候用的equals方法。

因為str==exit str為string類,是引用類型,其實是比較的兩個變量的地址值,exit並不是一個變量,
string類重寫了equals方法, object類的equals方法還是比較的對象的地址值,所以這麽寫不搭邊,基本數據類型用==判斷的是兩個值是否相等

java循環、數組練習