美国电话号码验证问题

发布于 2024-11-16 19:37:03 字数 2212 浏览 4 评论 0原文

我在我的班级中使用这段代码时遇到了问题:以下是问题

1.) 成功后它不会循环

(代码可以编译,但是当它询问“你的号码是多少?”并且我输入 909-8930 时,输出只是答案:正确,直到退出(使用电话号码)。我假设它会循环?)

2.)由于括号中的原因而给出错误:

phone = phone.replaceAll("(","");

phone = phone.replaceAll(")","");

但当我注释掉它们并离开时效果很好: phone = phone.replaceAll("-","");

3.) 没有使用布尔命令的最大字符验证。 (我们必须使用我们在课堂上学到的代码)

我正在使用 Vista(我知道,都很糟糕)cmd 来编译 Java 代码。

/* 


 */
import java.util.Scanner; // 
public class PhoneNumber

{

    //********number()******
    public static boolean Number(String str)

    {
        int n=0;
        while(n<str.length()) //while condition for the loop
        {
            char c=str.charAt(n);

            if(!(c>='0'&&c<='9'))return(false);//0 to 9
            n++; // counter and checked loop?

        }   
        return (true);
    }    
    // Phone Number

    public static void main(String[] args)

    {


        // Create a Scanner object to read input.
        String phone;
        Scanner sc = new Scanner(System.in);


        // Get the favorite city
        System.out.print("What is your phone number?");  // no ln
        phone=sc.nextLine( );


        //replace all perenthesis and dashes

        phone = phone.replaceAll("-",""); 
        phone = phone.replaceAll("(","");
        phone = phone.replaceAll(")","");


        // validation of number
        if(Number(phone))
        {

            // sub stuff to add back the dash and whateves
            String first,middle,last;
            first = phone.substring (0,3);
            middle = phone.substring (3,6); 
            last = phone.substring (6);
            String phonea = "("+ first + ")" +"-"+middle+ "-"+last; 


            // print stuff back 
            System.out.println ("correct until exit"+ phonea);

            // condition to exit    
            if (phone.equalsIgnoreCase("quit")); //not working?
            if (phone.equalsIgnoreCase("end"));
            if (phone.equalsIgnoreCase("stop"))System.exit(0); 
        }
        else
        {
            System.err.println("error-incorrect format: "+ phone); //error

        }    
    }
}

I'm having trouble with this code for my class : Here are the problems

1.) It does not Loop after success

(the code compiles but the when it asks "what is your number?" and i type 909-8930 the output just answers :correct until exit (with the phone number). I was under the assumption that its suppose to loop?)

2.) gives an error due to the parenthesis in:

phone = phone.replaceAll("(","");

phone = phone.replaceAll(")","");

but works fine when i comment them out and leave:
phone = phone.replaceAll("-","");

3.) does not have a max character validation using the boolean command. (we have to use code we've learned in class)

I'm using Vista (I know, all bad) cmd to compile the Java code.

/* 


 */
import java.util.Scanner; // 
public class PhoneNumber

{

    //********number()******
    public static boolean Number(String str)

    {
        int n=0;
        while(n<str.length()) //while condition for the loop
        {
            char c=str.charAt(n);

            if(!(c>='0'&&c<='9'))return(false);//0 to 9
            n++; // counter and checked loop?

        }   
        return (true);
    }    
    // Phone Number

    public static void main(String[] args)

    {


        // Create a Scanner object to read input.
        String phone;
        Scanner sc = new Scanner(System.in);


        // Get the favorite city
        System.out.print("What is your phone number?");  // no ln
        phone=sc.nextLine( );


        //replace all perenthesis and dashes

        phone = phone.replaceAll("-",""); 
        phone = phone.replaceAll("(","");
        phone = phone.replaceAll(")","");


        // validation of number
        if(Number(phone))
        {

            // sub stuff to add back the dash and whateves
            String first,middle,last;
            first = phone.substring (0,3);
            middle = phone.substring (3,6); 
            last = phone.substring (6);
            String phonea = "("+ first + ")" +"-"+middle+ "-"+last; 


            // print stuff back 
            System.out.println ("correct until exit"+ phonea);

            // condition to exit    
            if (phone.equalsIgnoreCase("quit")); //not working?
            if (phone.equalsIgnoreCase("end"));
            if (phone.equalsIgnoreCase("stop"))System.exit(0); 
        }
        else
        {
            System.err.println("error-incorrect format: "+ phone); //error

        }    
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

莳間冲淡了誓言ζ 2024-11-23 19:37:03

应用程序终止的原因与您如何确定应用程序的下一个状态应该是什么有关。查看正确电话号码大小写末尾的代码:

        // print stuff back 
        System.out.println ("correct until exit"+ phonea);

        // condition to exit    
        if (phone.equalsIgnoreCase("quit")); //not working?
        if (phone.equalsIgnoreCase("end"));
        if (phone.equalsIgnoreCase("stop"))
            System.exit(0);

本质上,您的目的是查看 String 变量 phone 是否包含用户请求的状态更改(因此,“继续”或“退出”将是我的猜测)。由于 phone 只是号码的数字(或某种错误的输入),因此不会为您提供状态信息。反过来,这些案例也很少是真实的。

验证后需要做的是请求用户提供正确的输入,以便应用程序可以确定下一个状态应该是什么。由于我们(SO 用户)不确切知道该程序的规范是什么,因此我们无法确定您到底需要做什么。但是,它可能看起来像这样:

System.out.println("What would you like to do?");
String nextState = sc.nextLine();

while (!nextState.equals("quit") && !nextState.equals("exit")) {
    //Do what you need to do (read the phone number, validate it, etc)

    System.out.println("What would you like to do?");
    String nextState = sc.nextLine();
}

System.out.println("End of application");

这本质上使应用程序能够控制确定应用程序何时启动和停止。虽然用户不希望应用程序停止,但您不断要求用户提供电话号码以进行验证。

虽然这并不是您遇到的问题的完整答案,但它应该可以为您提供一些有关解决某些应用程序问题的不错的指导。

The reason for the termination of your application has to do with how you determine what the next state of the application should be. Look at the code at the end of the correct phone number case:

        // print stuff back 
        System.out.println ("correct until exit"+ phonea);

        // condition to exit    
        if (phone.equalsIgnoreCase("quit")); //not working?
        if (phone.equalsIgnoreCase("end"));
        if (phone.equalsIgnoreCase("stop"))
            System.exit(0);

Essentially, your intent is to see if the String variable phone contains the state change requested by the user (so, "continue" or "quit" would be my guess). Since phone is just the digits of the number (or some kind of bad input) this will not give you the state information. In turn, these cases will rarely ever be true.

What you need to do post-validation is request that the user provide proper input so the application can determine what the next state should be. Since we (SO users) don't know exactly what the specification of the program is, we cannot determine what exactly you need to do. However, it would probably look something like this:

System.out.println("What would you like to do?");
String nextState = sc.nextLine();

while (!nextState.equals("quit") && !nextState.equals("exit")) {
    //Do what you need to do (read the phone number, validate it, etc)

    System.out.println("What would you like to do?");
    String nextState = sc.nextLine();
}

System.out.println("End of application");

This essentially gives the application control in determining when the application should start and stop. While the user does not wish for the application to stop, you keep asking the user for phone numbers to validate.

While this isn't the entire answer to the issues you're having, it should hopefully give you some decent guidance on fixing some of the applications issues.

最美不过初阳 2024-11-23 19:37:03

关于 1:如果您希望程序要求第二个输入,您需要告诉它这样做。主函数中的所有内容仅被调用一次。您可以将所有内容放入一个循环中,您要求

while (!phone.equalsIgnoreCase("quit")) {

}

这将循环,直到您输入 quit。

到目前为止,您的退出条件不起作用,因为您在 if 语句后面留下了分号。因此,编译器认为该行已经结束并跳转到下一行。

 if (phone.equalsIgnoreCase("quit")); //remove the semicolon in this line, otherwise System.exit will never be called.

您还将这些行放入 if (Number(phone)) 语句中。但由于“quit”不是一个数字,当你真正输入quit时,你永远不会到达这行代码。

About 1: If you want the program to ask for a second input you need to tell it to do so. Everything in the main function is only called once. You can put everything in a loop where you ask

while (!phone.equalsIgnoreCase("quit")) {

}

This would loop until you enter quit.

So far your exit conditions do not work, because you left the semicolon behind your if-statement. Because of this the compiler thinks that the line is over and jumps into the next line.

 if (phone.equalsIgnoreCase("quit")); //remove the semicolon in this line, otherwise System.exit will never be called.

Also you put these lines into the if (Number(phone)) statement. But as "quit" is not a number, you will never reach this line of code when you actually entered quit.

山色无中 2024-11-23 19:37:03

一般来说,如果您不明白代码在做什么,我建议:

  • 尝试从程序中删除内容(在制作备份副本之后),直到您得到一个简短的简单示例来说明您不理解的内容。当你可以找出其中较小的一部分时,为什么要尝试找出一个大的模糊问题呢?
  • 通过在整个代码中添加诸如 System.out.println('reached line 17') 之类的语句来进行实验,以查看程序执行操作的顺序。

也就是说,这里有一些(部分)答案。

1)成功后不循环

循环重复执行其中的语句。听起来您想要重复的是程序的大部分或全部:

  1. 从键盘读取字符串
  2. ,从其中删除某些字符字符串
  3. 如果剩余的字符串是数字,则将其分成 3 部分,然后打印 正确

如果您希望一遍又一遍地重复这三个操作,则需要在执行这些操作的代码周围进行一个大循环三个动作。没有循环,没有重复。

(循环内的某处将是退出程序的代码如果输入字符串是“quit”等)

2) 由于括号而出错:phone = phone.replaceAll("(","");

要解决此问题,您需要了解两件事。首先,replaceAll code> 将其第一个参数 "(" 视为正则表达式。不用担心它是什么,只需知道 replaceAll 赋予了特殊含义到 ( 字符而不是将其视为普通的旧 (。您可以通过在 ( 之前放置 \ 来告诉replaceAll正常对待它。\ 被称为“转义符”,因此字符串参数的内容应该是: \(

其次,你不能只输入 "\(" > 进入源代码,因为 Java 编译器本身会处理 \作为特殊字符。您必须添加一个反斜杠来告诉编译器正常处理另一个反斜杠,这听起来很荒谬,但事实就是如此。

phone = phone.replaceAll("\\(","");

3) 没有使用布尔命令的最大字符验证。

不确定您想要什么:检查它的字符数是否少于?无论哪种方式,您都可以编写一个if来检查phone.length()是否大于或小于某个数字。

In general, if you don't understand what your code is doing, I recommend:

  • Try to remove stuff from your program (after making a backup copy) until you have a short simple example of what you don't understand. Why try to figure out a large fuzzy problem when you could figure out a smaller piece of it?
  • Experiment by adding statements like System.out.println('reached line 17') all over the code to see the order in which your program is doing things.

That said, here are some (partial) answers.

1) It does not Loop after success

A loop repeatedly performs the statements inside of it. It sounds like what you want to be repeated is most or all of the program:

  1. read string from keyboard
  2. remove certain characters from the string
  3. if the remaining string is a number, separate it into 3 pieces, then print correct

If you want those three actions repeated over and over, you need to make a big loop around the code that does those three actions. No loop, no repetition.

(And somewhere inside that loop is going to be the code that exits the program if the input string is "quit", etc.)

2) gives an error due to the parenthesis in: phone = phone.replaceAll("(","");

To fix this you need to know two things. First, replaceAll treats its first argument "(" as a regular expression. Without worrying what that is, just know that replaceAll is giving a special meaning to the ( character rather than treating it as a plain old (. You can tell replaceAll to treat it normally by putting a \ before the (. The \ is called an "escape". So the contents of your string argument should be: \(

Second, you can't just type "\(" into your source code because the Java compiler itself treats \ as a special character. You have to add one more backslash to tell the compiler to treat the other backslash normally. It sounds absurd, but so it goes.

phone = phone.replaceAll("\\(","");

3) does not have a max character validation using the boolean command.

Not sure what you want here: checking that it has more or less than a certain number of characters? Either way, you could write an if to check whether phone.length() is more or less than some number.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文