简体   繁体   English

Java任务用字母和数字验证“课程代码”

[英]Java task Validate “course code” with letters and numbers

My question relates to an assignment that I have already turned in--but I want to figure out based on what I coded (which does some of the requirements) where I failed, what I did correctly, and if there was a better approach. 我的问题与我已经上交的作业有关,但是我想根据我在失败处所编码的内容(满足某些要求),正确执行的操作以及是否有更好的方法来进行计算。 Seriously novice to be clear. 认真的新手要弄清楚。

I've read through multiple previously asked questions and tried to put together information from those. 我已经阅读了多个先前提出的问题,并试图将这些问题的信息汇总在一起。

The task is to have the user input a six digit code--must meet these specifications: 任务是让用户输入六位数的代码-必须满足以下规范:

  1. have an upper or lower case 'I' as the first 首字母大写或小写“ I”
  2. have an upper or lower case 'T' as the second 大写或小写字母“ T”为第二个
  3. the third through sixth places must be digits 0-9 第三到第六位必须是数字0-9

if the entered code matches--the return is "course code validated" of it doesn't the return is "course code not valid" with the reason it is not. 如果输入的代码匹配,则返回的结果为“课程代码已验证”,否则返回的结果为“课程代码无效”,原因是返回的结果无效。

Pasting my code text below. 在下面粘贴我的代码文本。 Any feedback would be greatly appreciated. 任何反馈将不胜感激。

import java.util.Scanner; 
public class U4A1_sixthSession {


    public static void main(String[] args) {
        System.out.println("Amber's Copy");
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a course code to validate (e.g. IT4872):");
        String s = input.nextLine();


      if (s.charAt(0)!= 'i') {
    if (s.charAt(0)!=  'I') 
             System.out.println("Course Code must begin with the letter I." + "\n" +"Course code not valid.");

        else if (s.charAt(1)!=  't')
        if (s.charAt(1)!=  'T')
            System.out.println("Course Code must have second letter T." +"\n" + "Course code not valid.");

        else if (Character.isLetter(s.charAt(2))) 
            System.out.println("Course code must have digit in third spot." +"\n" + "Course code not valid.");
        else if (Character.isLetter(s.charAt(3))) 
            System.out.println("Course code must have digit in fourth place." +"\n" + "Course code not valid.");
        else if (Character.isLetter(s.charAt(4))) 
            System.out.println("Course code must have digit in fifth place." +"\n" + "Course code not valid.");
        else if (Character.isLetter(s.charAt(5))) 
            System.out.println("Course code must have digit in sixth place." +"\n" + "Course code not valid.");         
    else  
          System.out.println("Course code is valid."  + s);
    }
}
}

One thing that stands out to me would be that for checking the input an improvement could be instead of using the double if statements you could do: 对我而言突出的一件事是,为了检查输入,可以改进而不是使用double if语句,您可以这样做:

if(String.valueOf(s.charAt(0)).equalsIgnoreCase('i'))

if(String.valueOf(s.charAt(1)).equalsIgnoreCase('t'))

what this does is it checks for the letter no matter its case. 它的作用是无论大小写均会检查字母。

And for the numbers, you could do a for loop: 对于数字,您可以执行for循环:

for(int x = 2; x <= 5; ++x){

   if (Character.isLetter(s.charAt(x)))

       System.out.println(....);
}

These are purely improvements that would not only make your code work better, but also appear neater as well. 这些纯粹是改进,不仅会使您的代码更好地工作,而且看起来也更加整洁。

It is a better approach to test all the String throw functions like matches but that require you to know about regular expressions , it could be: 这是测试所有String抛出函数(如match )的更好方法,但需要您了解正则表达式 ,可能是:

import java.util.Scanner;
public class Holatadeo2016 {
    public static void main(String[] args) {

       System.out.println("Amber's Copy");
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a course code to validate (e.g. IT4872):");
        String s = input.nextLine();

        if(s.toLowerCase().matches("it[0-9][0-9][0-9][0-9]"))
            System.out.println("ok");
        else
            System.out.println("wrong");
    }
}

Here is an alternative way to do it hope it is useful. 这是一种替代方法,希望它有用。

public static void main(String[] args) {
            try {
                System.out.println("Amber's Copy");
                Scanner input = new Scanner(System.in);

                System.out.println("Enter a course code to validate (e.g. IT4872):");
                String s = input.nextLine();

                boolean hasSixDigits = s.length() == 6;
                boolean startsWithI = String.valueOf(s.charAt(0)).equalsIgnoreCase("i");
                boolean secondLetterT = String.valueOf(s.charAt(1)).equalsIgnoreCase("t");
                //will throw NumberFormatException if the 4 last chars are not numbers
                Integer.parseInt(s.substring(2));

                if (hasSixDigits && startsWithI && secondLetterT){
                    System.out.println("Valid course code");
                }
                else {
                    System.out.println("Invalid course code");
                    if (!hasSixDigits) {
                        System.out.println("Code should be a six digit code");
                    } 
                    if (!startsWithI) {
                        System.out.println("Code should start with I or i");
                    } 
                    if (!secondLetterT) {
                        System.out.println("Code's second letter should be T or t");
                    }
                }
            }catch(NumberFormatException nfe){
                System.out.println("Not valid third to last should be digits");
            }

From what i've seen your code is buggy, it failed to print valid/invalid for code starting with 'i' 从我发现您的代码有错误的地方来看,它无法打印以“ i”开头的代码有效/无效的代码

It also fail if you provide the following input "IT...." (.... = 4 spaces, they are not letters) 如果提供以下输入“ IT ....”(.. = 4个空格,它们不是字母),也会失败。

Then what if there are more than one error? 那如果有多个错误怎么办? You only print the first one due to nested "if else else if". 由于嵌套“ if else if”,您仅打印第一个。

To check string java (and other languages offer a better approach using regular expressions, please see below: 要检查字符串java(其他语言使用正则表达式提供了更好的方法,请参见以下内容:

public static void main(String[] args) {
        System.out.println("Amber's Copy");
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a course code to validate (e.g. IT4872):");
        String s = input.nextLine();

        Pattern pattern = Pattern.compile("^([i|I])(t|T)([0-9])([0-9])([0-9])([0-9])$");
        Matcher m = pattern.matcher(s);

        if (m.matches()) {
            System.out.println("Course code is valid." + s);
        } else {
            if (s.charAt(0) != 'i' && s.charAt(0) != 'I') {
                System.out.println("Course Code must begin with the letter I.");
            }
            if (s.charAt(1) != 't' && s.charAt(1) != 'T') {
                System.out.println("Course Code must have second letter T.");
            }
            if (!Character.isDigit(s.charAt(2))) {
                System.out.println("Course code must have digit in third spot.");
            }
            if (!Character.isDigit(s.charAt(3))) {
                System.out.println("Course code must have digit in fourth place.");
            }
            if (!Character.isDigit(s.charAt(4))) {
                System.out.println("Course code must have digit in fifth place.");
            }
            if (!Character.isDigit(s.charAt(5))) {
                System.out.println("Course code must have digit in sixth place.");
            }
            System.out.println("Course code not valid.");
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM