- import java.util.*;
- public class GradeRank{
- public static void main(String[] args){
- //scan to get the input number
- Scanner scan = new Scanner(System.in);
- //set a string to accept the input string
- String grade = null;
- while(true){
- sop("please input a num");
- //get the input string
- grade = scan.next();
- if(grade.equals("over"))//if the string is over,exit
- break;
- String reg = "\\d+";
- //judge if no input or format is wrong
- if(grade != null && grade.matches(reg))
- try{
- //rank the grade
- rank(Integer.valueOf(grade));
- }catch(Exception e){
- //print the exception
- sop(e.toString());
- }
- else{
- sop("please input the right format");
- sop("");
- continue;
- }
- sop("");
- }
- }
- public static void rank(int grade) throws Exception{
- //handle the num from large to small
- if(grade > 100){
- //throw exception
- throw new Exception("out the range");
- }else if(grade >= 90){
- //judge and print if grade is you
- sop(grade + ": excellent");
- }else if(grade >= 89){
- //judge and print if grade is liang
- sop(grade + ": good");
- }else if(grade >= 79){
- //judge and print if grade is zhong
- sop(grade + ": juts so so");
- }else if(grade >= 60){
- //failed
- sop(grade + ": just pass");
- }else{
- sop("failed");
- }
- }
- // a method to print
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
复制代码
2题- import java.util.*;
- public class ChangeCase{
- public static void main(String[] args) throws Exception{
- //scan to get the input
- Scanner scan = new Scanner(System.in);
- //set a string to accept the input string
- String s = scan.next();
- //print the string
- System.out.println(s);
- //print new string
- System.out.println(changeCase(s));
- }
- //the method to changeCase
- public static String changeCase(String s) throws Exception{
- //new string to store new string
- String news = "";
- //regex to judge if the sting is in right format
- String reg = "\\w+";
- if(!s.matches(reg)){//if not throw Exception
- throw new Exception("wrong format!");
- }
- //to change the string
- for(int x = 0; x < s.length(); x++){
- //get the char at index x
- char c = s.charAt(x);
- //judge if the number
- if(c >= '0' && c <= '9')
- //change to "#"
- news += "#";
- //judge if upcase
- else if(c >= 'A' && c <= 'Z')
- //change to lowcase
- news += (char)(c + 32) + "";
- //judge if lowcase
- else if(c >= 'a' && c <= 'z')
- //change to upcase
- news += (char)(c - 32) + "";
- }
- //return new string
- return news;
- }
- }
复制代码
谢谢版主的阅览!
|