0

例如 if (NUM4>-1) { System.out.println("您的语句中有无效字符,请重试。"); EMAIL = UI.nextLine(); "return to line '#'" } 我需要有一种方法可以返回到特定的代码行,而不是用 .break 结束程序

编辑好吧,到目前为止,这是我的代码。

package cormier.email.checker;

import java.util.Scanner;
import java.lang.String;
public class CormierEmailChecker {

/*

 */

public static void main(String[] args) {
    Scanner UI = new Scanner(System.in);
    String EMAIL, EMAILSPACE, EMAILCHECK1;
    int NUM1,NUM2,NUM3,NUM4,test;
    System.out.println("Please enter your E-Mail address.");
    EMAIL = UI.nextLine();
    NUM1 = EMAIL.indexOf("@");
    NUM2 = EMAIL.indexOf("#");
    NUM3 = EMAIL.indexOf("!");
    NUM4 = EMAIL.indexOf(" ");
    test = 0;
   while(test == 0){
       test=1;
    if (NUM4>-1) {
        System.out.println("Invalid character in E-Mail address, please try again.");
        EMAIL = UI.nextLine();
        NUM4 = EMAIL.indexOf(" ");
        test=0;
    }
    else if(NUM1==-1) {
        System.out.println("E-Mail address is missing an '@' symbol");
        EMAIL = UI.nextLine();
        NUM1 = EMAIL.indexOf("@");
        test=0;
    }
    else if(NUM1==0) {
        System.out.println("E-Mail shouldn't start with an '@' symbol");
        EMAIL = UI.nextLine();
        NUM1 = EMAIL.indexOf("@");
        test=0;
    }
    else if(NUM2>-1) {
        EMAIL = UI.nextLine();
        NUM2 = EMAIL.indexOf("#");
        test=0;
    }
    else if(NUM3>-1) {
        System.out.println("Invalid character in E-Mail address, please try again.");
         EMAIL = UI.nextLine();
         NUM3 = EMAIL.indexOf("!");
        test = 0;    
    }


   }

    if(EMAIL.endsWith(".ca") || EMAIL.endsWith(".com")) {

    }
    else {
        System.out.println("Please restart program");
    }  
}

}
4

3 回答 3

1

我需要有一种方法可以返回到特定的代码行,而不是用 .break 结束程序

不幸的是,你不会在这里得到你“需要”的东西。Java 没有 goto 语句。但是,永远不需要 goto。例如:

//code
if(condition)
    goto code

是相同的

do {
    //code
} while(condition);

您想要的任何逻辑都可以使用 while/if/for 和方法实现。如果您发布更多代码,我们可能会帮助您弄清楚要使用什么。

于 2013-11-14T15:31:15.223 回答
0

你可以写一个方法

public static String message(int n){
    if (n == 1) {
        return "Hello, World!";
    } else if (n == 2){
        return "Hello Planet!";
    } else if (n == 3){
        return "Hello Universe!";
    } else {
        return "Where are my Dragons?!";
    }
}

System.out.println(message(2));
于 2013-11-14T15:30:08.033 回答
0

您可以将控制流更改为类似

boolean valid = false;
<Ask the user to enter a value>
while(!valid) 
{
    <Have the user enter a value>
    if (value is valid) 
         valid = true;
    else
         print <error message>;
}

<Use the value>
于 2013-11-14T15:30:49.017 回答