【问题标题】:I keep getting "Invalid constant error" on my program and I am not sure why?我的程序不断收到“无效的常量错误”,我不知道为什么?
【发布时间】:2016-11-01 18:49:44
【问题描述】:

这是我计算 ISBN 13 号的代码,但我似乎遇到了问题。它一直给我一个关于无效字符常量的返回错误,每次我更改它时,它都会在方法名称上给出一个错误,我不明白为什么。

import java.util.Scanner;

    public class ISBN {

public static int VerifyISBN(String isbn) {
    if(isbn.matches("[0-9]+") && isbn.length() > 12){
    for(int i = 0; i < 12; i++){
        char digit = isbn.charAt(i);
        int sum = 0;
        if (Character.isDigit(digit)){
            int digitValue = digit - '0';
            if(i % 2 == 0)
                sum += digitValue;
            else sum += 3 * digitValue;
        }
        else 
            return 'invalid'; (This is where I get the error)
        }
    }
}

public static void main(String[] args) {
    final String TITLE = "ISBN-13 Identifier";

    System.out.println("Welcome to the " + TITLE);
    Scanner input = new Scanner(System.in);

    String response;
    do {
        System.out.print("Enter the first 12 digits of an ISBN-13: ");
        String isbn = input.nextLine().trim();

        //String isbnVerifier = generateISBN(isbn);
        //if(isbn.equals("INVALID"));

        System.out.println("The 13th number of" + isbn + " is " +
            ((verifyISBN(isbn))));

        System.out.print("Do this again? [nY]");
        response = input.nextLine().toUpperCase();

    } while (!response.equals("N"));

    input.close();
    System.out.println("Thank you for using the " + TITLE);

}

}

【问题讨论】:

  • 'invalid' 无效

标签: java eclipse loops return


【解决方案1】:

两个问题:

  1. 文字'invalid' 是不正确的Java 语法。字符串用双引号分隔。单引号用于分隔单字符文字,例如'a',但不能用于字符串。
  2. 该方法被声明为返回一个整数,因此您不能返回String

如果您的意图是返回一个指示输入无效的标记值,您可能应该使用-1 之类的东西,然后调用者可以将其解释为错误条件。

或者,您可以定义引发异常的方法。

【讨论】:

  • 当我使用 -1 时,它给我一个错误的方法,说该方法必须返回一个 int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 2020-08-02
  • 2017-11-23
相关资源
最近更新 更多