【程序7】题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为 '\n '.
- import java.util.Scanner;
- public class ex7 {
- public static void main(String args[]){
- System.out.println("请输入字符串:");
- Scanner scan=new Scanner(System.in);
- String str=scan.next();
- String E1="[\u4e00-\u9fa5]";
- Sintrting E2="[a-zA-Z]";
- countH=0;
- int countE=0;
- char[] arrChar=str.toCharArray();
- String[] arrStr=new String[arrChar.length];
- for (int i=0;i
- arrStr[i]=String.valueOf(arrChar[i]);
- }
- for (String i: arrStr ){
- if (i.matches(E1)){
- countH++;
- }
- if (i.matches(E2)){
- countE++;
- }
- }
- System.out.println("汉字的个数"+countH);
- System.out.println("字母的个数"+countE);
- }
- }
import java.util.Scanner; public class ex7 { public static void main(String args[]){ System.out.println("请输入字符串:"); Scanner scan=new Scanner(System.in); String str=scan.next(); String E1="[\u4e00-\u9fa5]"; Sintrting E2="[a-zA-Z]"; countH=0; int countE=0; char[] arrChar=str.toCharArray(); String[] arrStr=new String[arrChar.length]; for (int i=0;i arrStr[i]=String.valueOf(arrChar[i]); } for (String i: arrStr ){ if (i.matches(E1)){ countH++; } if (i.matches(E2)){ countE++; } } System.out.println("汉字的个数"+countH); System.out.println("字母的个数"+countE); } }
【程序8】题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
程序分析:关键是计算出每一项的值。
- import java.io.*;
- public class Sumloop {
- public static void main(String[] args) throws IOException{
- int s=0;
- String output="";
- BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("请输入a的值");
- String input =stadin.readLine();
- for(int i =1;i<=Integer.parseInt(input);i++){
- output += input;
- int a = Integer.parseInt(output) ;
- s+=a;
- }
- System.out.println(s);
- }
- }
import java.io.*; public class Sumloop { public static void main(String[] args) throws IOException{ int s=0; String output=""; BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请输入a的值"); String input =stadin.readLine(); for(int i =1;i<=Integer.parseInt(input);i++){ output += input; int a = Integer.parseInt(output) ; s+=a; } System.out.println(s); } }
另解:
- import java.io.*;
- public class Sumloop {
- public static void main(String[] args) throws IOException{
- int s=0;
- int n;
- int t=0;
- BufferedReader stadin = new BufferedReader(new InputStreamReader(System.in));
- String input = stadin.readLine();
- n= Integer.parseInt(input);
- for(int i=1;i<=n;i++){
- t=t*10+n;
- s=s+t;
- System.out.println(t);
- }
- System.out.println(s);
- }
- }