Не найти аргумента в классе драйвера в Java - PullRequest
0 голосов
/ 27 февраля 2020

Я столько всего перепробовал и потратил бесчисленные часы на эту проблему без всякой удачи. У меня есть класс, который должен получить месяц, который пользователь вводит как int, и использовать инструкцию switch для преобразования в строку (соответствующий месяц). Я перепробовал много вещей, но по какой-то причине я получаю ошибку, что требуемые и найденные аргументы различаются по длине. (Я пробовал много вещей, таких как простое использование SOP, toString и других, но пока ничего не получалось)

Резюме: превратить целое число в строку с помощью оператора switch. класс драйвера:

import java.util.Scanner;
/**
 * Write a description of class TestMonthDays here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class TestMonthDays
{
    public static void main(String[] args)
    {
        //Creates scanner
        Scanner keyboard = new Scanner(System.in);

        //Brings the MonthDays class into the test class
        MonthDays date;
        date = new MonthDays();

        //Asks user for number 1-12 and if its not between that range then asks the user again
        System.out.print ("Enter the number of a month [1-12]: ");
        int numberMonth = keyboard.nextInt();

        while (!(numberMonth >= 1 && numberMonth <= 12))
        {
            System.out.print ("Please enter a number of a month between 1 and 12: ");
            numberMonth = keyboard.nextInt();
        }

        //Gets the year that the user inputs
        System.out.print ("\nEnter the number of a year, greater than 0: ");
        int year = keyboard.nextInt();

        while (year < 0)
        {
            System.out.print ("Please enter the number of a year that is greater than 0: ");
            year = keyboard.nextInt();
        }

        System.out.println ("\nThe number of days in " + date.getMonth() + ", " + year + " is: ");
    }
}

А вот метод и конструктор Speci c в моем другом классе, с которыми я борюсь:


/**
 * Write a description of class MonthDays here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class MonthDays
{
    // instance variables 
    int month;
    int year;
    String thisMonth;
    public void date() //Default Constructor
    {
        month = 0;
        year = 0;
        thisMonth = "";
    }


    public String getMonth(int month)
    {
        switch (month) 
        {
            case 1:
                thisMonth = ("January");
                break;
            case 2: 
               thisMonth = ("February");
                break;
            case 3:
                thisMonth = ("March");
                break;
            case 4:
                thisMonth = ("April");
                break;
            case 5:
                thisMonth = ("May");
                break;
            case 6: 
                thisMonth = ("June");
                break;
            case 7:
                thisMonth = ("July");
                break;
            case 8:
                thisMonth = ("August");
                break;
            case 9:
                thisMonth = ("September");
                break;
            case 10:
                thisMonth = ("October");
                break;
            case 11:
                thisMonth = ("November");
                break;
            case 12:
                thisMonth = ("December");
                break;
        }
        return thisMonth;
    }
}

Ответы [ 2 ]

0 голосов
/ 27 февраля 2020

Вы вызываете метод getMonth без аргументов. Просто измените

System.out.println ("\ nКоличество дней в" + date.getMonth () + "," + year + "is:");

на

System.out.println ("\ nКоличество дней в" + date.getMonth (numberMonth) + "," + year + "is:");

0 голосов
/ 27 февраля 2020

Первый

public void date() //Default Constructor

- это неправильно . Имя конструктора должно совпадать с именем класса и составляет , а не void.

public MonthDays() // <-- No-arg constructor, if you provide any constructor
                   //     there is no default constructor.

Во-вторых, вы должны отделить лог c для определения названия месяца от установки значения , И я бы предпочел метод static и Map для этого. Например,

private static Map<Integer, String> monthMap = new HashMap<>();
static {
    String[] names = { "January", "February", "March", "April", //
            "June", "July", "August", "September", "October", //
            "November", "December" };
    for (int i = 0; i < names.length; i++) {
        monthMap.put(i + 1, names[i]);
    }
}

// Could be public, just a utility method
private static String getMonthName(int month) {
    return monthMap.getOrDefault(month, "Unknown");
}

Затем используйте что-то вроде

public String getMonth() {
    return getMonthName(this.month);
}
...