2014年7月12日 星期六

java程式設計題目---數字處理【(for loop && while loop)輸出、換行】

設計一個程式,由使用者從螢幕輸入正整數n、m,將n至m所有整數由小至大印出,但每列指印出最多7個數字,如果輸入m小於(等於)n,則輸出沒有結果。【使用for loop 和 while loop 撰寫】(每一橫排、直排皆須對齊)範例如下:








  1. import java.util.Scanner;
  2.  
  3. public class C1
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8. Scanner input = new Scanner(System.in);
  9. //請使用者輸入顯示數字範圍
  10. System.out.println("請輸入起始數字:");
  11. int start = input.nextInt();
  12. System.out.println("請輸入結束數字:");
  13. int end = input.nextInt();
  14. int countwhile = 0;
  15. int countfor = 0;
  16. int number = start;
  17. while(start == end || start > end)
  18. {
  19. countfor = countfor - 100;
  20. countwhile = countwhile - 100;
  21. System.out.println("沒有結果"); break;
  22. }
  23. for(int n = start ; n <= end ; n++)//使用for loop 撰寫程式
  24. {
  25. countfor = countfor + 1;
  26. if( countfor % 7 != 0 && countfor > 0)
  27. {
  28. System.out.printf("%7d",n);
  29. }
  30. else if(countfor % 7 == 0 && countfor > 0 )
  31. {
  32. System.out.printf("%7d\n",n);
  33. }
  34. }
  35. System.out.println("");//幫助排版更清楚
  36. System.out.println("");//幫助排版更清楚
  37. while( number <= end && countwhile >= 0 )//使用while loop 撰寫程式
  38. {
  39. countwhile = countwhile + 1;
  40. if(countwhile % 7 != 0)
  41. {
  42. System.out.printf("%7d",number);
  43. }
  44. else if(countwhile % 7 == 0)
  45. {
  46. System.out.printf("%7d\n",number);
  47. }
  48. number = number + 1;
  49. }
  50. }
  51.  
  52. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...