Java基礎(chǔ)題新手練習(三)
水仙花數(shù)
求出0~999之間的所有“水仙花數(shù)”并輸出。(“水仙花數(shù)”是指一個三位數(shù),其各位數(shù)字的立方和確好等于該數(shù)本 身,如;153=1+5+3?,則153是一個“水仙花數(shù)“。)
源碼
public static void GetDaffodil(){
int j=0;
int k=0;
int l=0;
for(int i=0;i<=999;i++){
j=i/100;
k=(i-j*100)/10;
l=(i-j*100-k*10);
if(j*j*j+k*k*k+l*l*l==i){
System.out.println(i+"是水仙花數(shù)");
// continue;
}
}
}
運行結(jié)果:

計算分數(shù)的值
計算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值 。
源碼
public static double GetSum(){
double sum= 0;
int flag = 1;
for (double i = 1;i<=100;i++) {
sum+=(1/i)*flag;
flag=-flag;
}
return sum;
}
運行結(jié)果:

最大公約數(shù)
求兩個正整數(shù)的最大公約數(shù)
源碼
public static void Getgcd(int a,int b){
int c= a%b;
while(c!=0){
a = b;//18
b = c;//6
c = a % b;
}
System.out.println(b+"是a和b的最大公約數(shù)");
}
運行結(jié)果:

二進制1的個數(shù)
求一個整數(shù),在內(nèi)存當中存儲時,二進制1的個數(shù)
源碼
public static int Getnum(int n){
int count = 0;
while(n!=0){
if((n&1)!=0) {
n = n >>> 1;
count++;
}
}
return count;
}
運行結(jié)果:

二進制序列
獲取一個數(shù)二進制序列中所有的偶數(shù)位和奇數(shù)位, 分別輸出二進制序列
源碼
public static void getBinnum(){
Scanner sc= new Scanner(System.in);
int num=sc.nextInt();
System.out.print("odd sequence:");
for(int i=30;i>=0;i-=2){
System.out.print((num>>i)&1);
}
System.out.print(" even sequence:");
for(int i=31;i>0;i-=2){
System.out.print((num>>i)&1);
}
sc.close();
}
運行結(jié)果:

模擬登陸
編寫代碼模擬三次密碼輸入的場景。 最多能輸入三次密碼,密碼正確,提示“登錄成功”,密碼錯誤, 可以重新輸 入,最多輸入三次。三次均錯,則提示退出程序
源碼
public static void GetPasswd(){
int count = 3;
while (count != 0) {
Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
if(password.equals("1234")) {
System.out.println("登錄成功!");
break;
}else {
count--;
System.out.println("還有"+count+"次機會!");
}
}
運行結(jié)果:

輸出一個整數(shù)的每一位
輸出一個整數(shù)的每一位,如:123的每一位是1 , 2 , 3
源碼
public static void getdigit(){
System.out.println("請輸入三位數(shù)整數(shù):");
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int i=n/100;
int j=(n-i*100)/10;
int k=(n-i*100-j*10);
System.out.println(n+"分解為"+i+" "+j+" "+k);
}
運行結(jié)果:

輸出乘法口訣表
輸出n*n的乘法口訣表,n由用戶輸入。
源碼
public static void PrintMultiption1(){
System.out.println("請輸入n的值: ");
Scanner scanner = new Scanner(System.in);
int n =scanner.nextInt();
for(int i= 1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i<=j)
System.out.print(i+"*"+j+"="+i*j+" ");
}
System.out.println( );
}
}
運行結(jié)果:

總結(jié)
本篇java基礎(chǔ)練習題就到這里了,希望對你有所幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
spring mvc @PathVariable綁定URI模板變量值方式
這篇文章主要介紹了spring mvc @PathVariable綁定URI模板變量值方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

