杭电ACM2024java做法

来源:互联网 发布:月球背面的秘密知乎 编辑:程序博客网 时间:2024/04/28 10:33
C语言合法标识符

Problem Description
输入一个字符串,判断其是否是C的合法标识符。

Input
输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然后是n行输入数据,每行是一个长度不超过50的字符串。

Output
对于每组输入数据,输出一行。如果输入数据是C的合法标识符,则输出"yes",否则,输出“no”。

Sample Input
3
12ajf
fi8x_a
ff  ai_2

Sample Output
no
yes

no

我是这么做的

import java.util.Scanner;public class Main{    public static void main(String[] args){        Scanner scanner=new Scanner(System.in);        while(scanner.hasNext()){            int n=scanner.nextInt();            for(int i=0;i<n;i++){                String s=scanner.next();                char[] s2=s.toCharArray();                boolean flag=true;//                for(int j=0;j<s2.length;j++){//                    System.out.println(s2[j]);//                }                if((s2[0]>=65&&s2[0]<=90)||(s2[0]>=97&&s2[0]<=122)){                    for(int a=1;a<s2.length;a++){                        if((s2[0]>=65&&s2[0]<=90)||(s2[0]>=97&&s2[0]<=122)||(Character.isDigit(s2[a])||(s2[a]=='_'))){                                                    }                        else{                            flag=false;                            break;                        }                    }                    if(flag) System.out.println("yes");                    else System.out.println("no");                }                else{                    System.out.println("no");                }            }        }    }}

奇了怪了,这样就不行

import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;public class Main{    public static void main(String[] args) throws IOException {        // TODO Auto-generated method stub        Scanner s = new Scanner(new BufferedInputStream(System.in));        int n;        char c;        boolean b;        while (s.hasNext()) {            n = s.nextInt();            String str = s.nextLine();            String[] ar = new String[n];            for (int i = 0; i < n; ++i) {                ar[i] = s.nextLine();                b = true;                for (int j = 0; j < ar[i].length(); ++j) {                    c = ar[i].charAt(j);                    if (j == 0) {                        if (Character.isLetter(c) || c == '_') {                        } else {                            b = false;                            break;                        }                    } else {                        if (c == '_' || Character.isDigit(c)                                || Character.isLetter(c)) {                        } else {                            b = false;                            break;                        }                    }                }                if (b) {                    System.out.println("yes");                } else                    System.out.println("no");            }        }    }}

别人的正确答案是这样的,说实话,我感觉我的更加简介易懂,但是既然错了,肯定有错的地方,我再仔细看看吧

0 0