Java初學練習答案(迴圈)

來源:互聯網
上載者:User

標籤:

/*題目如下:1 (for 迴圈)*編程找出四位整數abcd 中滿足下述關係的數。(ab+cd)(ab+cd)=abcd2 (迴圈)*讀入一個整數n,輸出如形n = 3  * ********n = 4   *  *** ************思路:讀入的整數n,就是外層迴圈的迴圈次數。對於每一行,要做的事情:1. 輸出若干個空格;2. 輸出若干個星;3. 換行。提示:輸出不換行,用System.out.print()3. (迴圈)**求水仙花數。所謂水仙花數,是指一個三位元abc,如果滿足a3+b3+c3=abc,則abc 是水仙花數。4. (迴圈)**輸入一個整數,計算它各位上數位和。(注意:是任意位的整數)空格: n-1 依次遞減   星號:1 3 5 71 2 3 4*/package MyTest;import java.util.Scanner;public class ChapUnitOne {//第一題答案public void AnswerOne(){int a,b,c,d;/*int i = 1234;a = i / 1000;b = i / 100 % 10;c = i / 10 % 10;d = i % 10;System.out.println(a);System.out.println(b);System.out.println(c);System.out.println(d);*/for(int i = 1000;i<9999;i++){a = i / 1000;b = i / 100 % 10;c = i / 10 % 10;d = i % 10;int ab = a*10+b;int cd = c*10+d;int ad = ab+cd;if(ad*ad == i){System.out.println(i);}}}//第二題答案public void AnswerTwo(){Scanner num = new Scanner(System.in);System.out.println("請輸入一個整數");int mynum = num.nextInt();for(int i=0; i<mynum; i++){for (int j=0; j<=mynum-i-1; j++){System.out.print(" ");}for (int j=0; j<=i*2; j++){System.out.print("*");}System.out.println();}}//第三題答案public void AnswerThree(){for(int i = 100;i<999;i++){int a = i / 100 % 10;int b = i / 10 % 10;int c = i % 10;if(a*a*a+b*b*b+c*c*c == i){System.out.println("該數字為水仙花數:"+i);}}}//第四題答案public void AnswerFour(){Scanner num = new Scanner(System.in);System.out.println("請輸入一個整數:");int mynum = num.nextInt();int sum = 0;/* int a = i / 100 % 10; int b = i / 10 % 10;     int c = i % 10;*/System.out.print("Sum = ");while (mynum>0){int temp = mynum%10;sum += mynum%10;mynum = mynum/10;if(mynum !=0 )System.out.print(temp+"+");elseSystem.out.print(temp);}System.out.println(" = "+sum);}public static void main(String[] args) {Scanner i = new Scanner(System.in);System.out.println("請輸入您想查看答案的題號:");int num = i.nextInt();ChapUnitOne myanswer = new ChapUnitOne();switch(num){case 1:myanswer.AnswerOne();break;case 2:myanswer.AnswerTwo();break;case 3:myanswer.AnswerThree();break;case 4:myanswer.AnswerFour();break;}}}

  

Java初學練習答案(迴圈)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.