2015-03-04 2 views
-3

Мне трудно понять, что делать дальше. Я довел этот код до этого момента. Мои инструкции заключались в том, чтобы создать валидатор кредитной карты без массива, мы - класс новичков в области компьютерных наук, и мы пока не дошли до этого. Вот мой код. Всякий раз, когда я компилирую код дает мне ошибку:Недостаток валидатора кредитной карты

«ява: 21: ошибка: метод IsValid в классе CreditCardValidator не может быть применен к данным типам; если (IsValid (карта)) { требуется: INT, INT, Строка найдена: String причины: фактические и формальные списки аргументов различаются по длине

/** 
    Credit Card Validator 

    @author Your Name 
    @date Today's Date 
    @class Our Class 
*/ 
import java.util.Scanner; 
public class CreditCardValidator { 

    public static void main (String[] args) { 
     String card = "4012888888881881"; 

     // When you are finished writing the methods below, 
     // uncomment the three lines below to test. 

     // Scanner input = new Scanner(System.in); 
     // System.out.print("Enter a Credit Card Number: "); 
     // String card = input.nextLine(); 

    if (isValid(card)) { 
     System.out.print("valid"); 
     } else { 
     System.out.print("invalid"); 
     // If False, state the card number is invalid 
    } 
     // System.out.println(getDigit(18) + " should be 9 "); 
     // System.out.println(getDigit(5) + " should be 5 "); 
     //System.out.println(sumOfDoubleEvenPlace(card+ "should be 47")); 
    } 

    /** 
     Returns true if the card number is valid 

     To determine if a card is valid, the sum of the Double Even Place 
     Numbers and the Sum of the Odd Place Numbers must be divisible by 
     ten (10), the String must be 13 to 16 digits, *and* the String must 
     start with "4", "5", "37", or "6". 

     @param number: A 13 to 16 digit String of numbers 

     @returns true if the String is a valid card, False otherwise 
    */ 
    public static boolean isValid(int totalEven, int totalOdd, String company) { 
     if (((totalEven + totalOdd) % 10 == 0) && company.equals("Visa")) { 
      return true; 
     } else { 
      if (((totalEven + totalOdd) % 10 == 0) && company.equals("Master Card")) { 
       return true; 
      } else { 
       if (((totalEven + totalOdd) % 10 == 0) && company.equals("American Express")) { 
        return true; 
       } else { 
        if (((totalEven + totalOdd) % 10 == 0) && company.equals("Discover Card")) { 
         return true; 
        } else { 
         return false; 
        } 
       } 
      } 
     } 
    }  
    /** 
     Double every second digit from *right to left*. 

     If doubling of a digit results in a two-digit number, add the two digits 
     together to get a single digit number using the getDigit(...) method. 

     Use a *loop* to cycle through all the numbers of the String. 
     Note: You will need to *convert a char to an int* 

     @param number: A 13 to 16 digit String of numbers 

     @returns an integer 
    */ 
    public static int sumOfDoubleEvenPlace(String number){ 
     int totalEven = 0; 
     int start = number.length() - 1; // starts at 14 
     // i = 14; 14 > 0; 14 -= 2 
     for (int i = start; i >= 0; i -= 2) { 
      char c = number.charAt(i); 
      int digit = Character.getNumericValue(c) * 2; 
      // System.out.println(digit + " " + getDigit(digit)); 
      totalEven += getDigit(digit); 
     } 
    return totalEven; // Total of double even place 
    } 
    /** 
     Return this number if it is a single digit, otherwise, return the sum 
     of the two digits. For example, 18 will return 9 (because 1 + 8) 
     @param number: a digit that will be between 0 and 18 
     @returns an integer 
    */ 
    public static int getDigit(int number){ 
    int calc = 0; 
    if (number < 10) { 
    // This is one digit 
    } else { 
     // This is two digits 
     calc = number - 9; 
    } 
    return calc; 
    } 
    /** 
     Return sum of odd-place digits in number 

     Use a *loop* to cycle through all the numbers of the String. 
     Note: You will need to *convert a char to an int* 

     @param number: A 13 to 16 digit String of numbers 

     @returns an integer 
    */ 
    public static int sumOfOddPlace(String number){ 
    int totalOdd = 0; 
    int start = number.length(); 

    for (int i = start; i >= 0; i -= 2) { 
     char c = number.charAt(i); 
     int digit = Character.getNumericValue(c) * 2; 

     totalOdd += getDigit(digit); 
    } 
    return totalOdd; 
    } 

    /** 
     Return the company of the card by looking at the character 
     at the zero (0) index of number. 

     @param number: A 13 to 16 digit String of numbers 

     @returns a String that is either 
     "Visa", "Master Card", "American Express", or "Discover Card" 
    */ 
    public static String getCompany(String number){ 
    int card = number.length(); 
    int i = card - number.length(); 
    char c = number.charAt(i); 
    int digit = Character.getNumericValue(c); 
    int d = i + 1; 
    String company = ""; 

    if (digit == 4) { 
     company = "Visa"; 
    } else if (digit == 5) { 
     company = "Master Card"; 
    } else if (digit == 6) { 
     company = "Discover Card"; 
    } else if (digit == 3 && d == 7) { 
     company = "American Express"; 
    } 
     return company; 
    } 
} 
+1

Как вы думаете, что означает ошибка? Позвольте мне подчеркнуть объявление 'isValid (int totalEven, int totalOdd, String company)' –

+0

Ваш метод 'isValid()' требует трех аргументов. Вы только предоставили один здесь 'if (isValid (card)) {' –

ответ

0

метод подпись public static boolean isValid(int totalEven, int totalOdd, String company)

в строке 21, вы вызываете его с помощью isValid(card), где карта представляет собой строку, «4012888888881881»

Ошибка говорит вам точно, что не так. Не задумываясь подробно, я подозреваю, что вам нужно будет сначала вызвать sumOfOddPlace() и sumOfDoubleEvenPlace() и использовать результаты для вызова isValid()

Если вы используете IDE, такую ​​как Eclipse или IntelliJ, он должен отметить это в редакторе

+0

Мне все еще трудно понять. Я использую Notepad ++. Фактический код был написан мной, но мой инструктор дал нам скелет, и нам сказали следовать этому формату. Я все еще смущен тем, как я буду отображать фактический тип кредитной карты и ее действительность? Можете ли вы привести мне пример? –

+0

# 1 Сделайте себе одолжение и загрузите IDE, это сделает вашу жизнь намного проще. Я рекомендую IntelliJ IDEA. https://www.jetbrains.com/idea/ – Jimmy

+0

# 2 читайте http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html, он должен очистить ваше замешательство вокруг аргументов метода – Jimmy

Смежные вопросы