JAVA經典算法40題(4)

 【程序7】題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。java

程序分析:利用while語句,條件爲輸入的字符不爲 '\n '.算法

Java代碼 複製代碼 收藏代碼
  1. import java.util.Scanner;
  2. public class ex7 {
  3. public static void main(String args[]){
  4. System.out.println("請輸入字符串:");
  5. Scanner scan=new Scanner(System.in);
  6. String str=scan.next();
  7. String E1="[\u4e00-\u9fa5]";
  8. Sintrting E2="[a-zA-Z]";
  9. countH=0;
  10. int countE=0;
  11. char[] arrChar=str.toCharArray();
  12. String[] arrStr=new String[arrChar.length];
  13. for (int i=0;i
  14. arrStr[i]=String.valueOf(arrChar[i]);
  15. }
  16. for (String i: arrStr ){
  17. if (i.matches(E1)){
  18. countH++;
  19. }
  20. if (i.matches(E2)){
  21. countE++;
  22. }
  23. }
  24. System.out.println("漢字的個數"+countH);
  25. System.out.println("字母的個數"+countE);
  26. }
  27. }

 

【程序8】題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。ide

程序分析:關鍵是計算出每一項的值。oop

Java代碼 複製代碼 收藏代碼
  1. import java.io.*;
  2. public class Sumloop {
  3. public static void main(String[] args) throws IOException{
  4. int s=0;
  5. String output="";
  6. BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
  7. System.out.println("請輸入a的值");
  8. String input =stadin.readLine();
  9. for(int i =1;i<=Integer.parseInt(input);i++){
  10. output += input;
  11. int a = Integer.parseInt(output) ;
  12. s+=a;
  13. }
  14. System.out.println(s);
  15. }
  16. }

另解:url

Java代碼 複製代碼 收藏代碼
  1. import java.io.*;
  2. public class Sumloop {
  3. public static void main(String[] args) throws IOException{
  4. int s=0;
  5. int n;
  6. int t=0;
  7. BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
  8. String input = stadin.readLine();
  9. n= Integer.parseInt(input);
  10. for(int i=1;i<=n;i++){
  11. t=t*10+n;
  12. s=s+t;
  13. System.out.println(t);
  14. }
  15. System.out.println(s);
  16. }
  17. }  
相關文章
相關標籤/搜索