检查方法是否定义了整数参数

huangapple go评论74阅读模式
英文:

Checking if an integer argument is defined for a method

问题

场景:我目前正在尝试在Java中制作一个日历,我创建的一个方法(getMonthSize)是获取一个月的大小(如下所示)。我当前的目标是使该方法无论用户是否定义了参数都能响应(如果参数留空,则返回当前月的大小,如果定义了参数,则返回输入月份的大小)。

努力:我在网上进行了相当彻底的搜索,找到了一些测试arg.length==0的答案(尽管结果只有当arg是String时才有效),还找到了一些类似"arg!==undefined"的答案(我认为这可能是JavaScript的用法),但都没有成功。我还了解到,如果整数没有初始化,其默认值将为0,这就是我尝试在我的代码中利用的,尽管似乎Java仍然希望我输入"0"才能使方法正常工作。

问题:我希望有一些命令可以检查参数是否为空,以允许我设置两种情况,并实现我想要的方法。

package model;

import java.util.Calendar;

public class myCalendar {
   private Calendar calendar = Calendar.getInstance();
   private int day = calendar.get(Calendar.DAY_OF_WEEK);
   private int date = this.calendar.get(Calendar.DAY_OF_MONTH);
   private int month = calendar.get(Calendar.MONTH) + 1;
   private int year = calendar.get(Calendar.YEAR);
   
   public void setCalendar(int Year, int Month, int Date) {
       this.calendar.set(Year, Month - 1, Date);
   }
   
   public int getDay() {
      return day;
   }
   
   public int getDate() {
       return date;
   }
   
   public int getMonth() {
       return month;
   }
   
   public int getYear() {
       return year;
   }
   
   public int getFirstDay() {
       Calendar test = this.calendar;
       test.set(year, month - 1, 1);
       return test.get(Calendar.DAY_OF_WEEK) - 1;
   }
   
   public int getMonthSize(int num) {
       int Month = 0;
       int days = 0;
       if (num > 0) {
           Month = num;
       } else {
           Month = month;
       }
       if (Month == 1 || Month == 3 || Month == 5 || Month == 7  
           || Month == 8 || Month == 10 || Month == 12) {   
           days = 31;   
       }   
       if (Month == 4 || Month == 6 || Month == 9 || Month == 11) {   
           days = 30;   
       }   
       if (Month == 2) {   
           if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {   
               days = 29;   
           } else {   
               days = 28;   
           }   
       }
       return days;
   }
   
   public String getNow() {
       String monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
       String a = monthNames[month - 1] + ", " + String.valueOf(year);
       return a;
   }
}
英文:

Scenario: I am currently attempting to make a calendar in Java, one of the methods I have created (getMonthSize) is to get the size of a month (as shown). My goal currently is to make the method respond regardless of whether the argument is defined by the user (give the current month size if argument left blank, and give the size of the inputted month if argument is defined).

Efforts: I have given quite a thorough search for an answer on the web, I have come across answers testing to see if the arg.length==0 (although it turns out that works only if the arg is a String), and answers using something along the lines of "arg!==undefined" (which I think may be for javascript), with no avail. I have also learned that if an integer is not initialized, its default value will be 0, so that is what I tried to take advantage of with my code shown, although it seemed that java still expects me to input "0" for the method to work.

Question: I am hoping there is some command that checks if the argument is left blank, allowing me to set 2 cases, and achieve what I want with the method.

package model;
import java.util.Calendar;
public class myCalendar {
private Calendar calendar=Calendar.getInstance();
private int day=calendar.get(Calendar.DAY_OF_WEEK);
private int date=this.calendar.get(Calendar.DAY_OF_MONTH);
private int month=calendar.get(Calendar.MONTH)+1;
private int year=calendar.get(Calendar.YEAR);
public void setCalendar(int Year, int Month, int Date){
this.calendar.set(Year,Month-1,Date);
}
public int getDay(){
return day;
}
public int getDate () {
return date;
}
public int getMonth(){
return month;
}
public int getYear() {
return year;
}
public int getFirstDay () {
Calendar test = this.calendar;
test.set(year, month-1, 1);
return test.get(Calendar.DAY_OF_WEEK)-1;
}
public int getMonthSize (int num) {
int Month=0;
int days=0;
if (num>0){
Month=num;
} else {
Month=month;
}
if(Month==1||Month==3||Month==5||Month==7  
||Month==8||Month==10||Month==12){   
days=31;   
}   
if(Month==4||Month==6||Month==9||Month==11)   
{   
days=30;   
}   
if(Month==2)   
{   
if(((year%4==0)&&(year%100!=0))||(year%400==0))   
{   
days=29;   
}   
else   
{   
days=28;   
}   
}
return days;
}
public String getNow () {
String monthNames[]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a=monthNames[month-1]+", "+String.valueOf(year);
return a;
}
}

答案1

得分: 0

我希望我正确理解了您的问题。

您的问题是,用户可以在没有有效参数的情况下启动该方法。如果您有一个前端,那么您也应该在那里捕捉它。但在后端(Java)中,您可以使用try块或简单的if-else来处理。

将Integer强制转换为String,然后使用正则表达式(可能类似于这样:

String text = num + "";
if (text != null && text.matches("\\d+")) {
    //...
}

或者您可以将整数强制转换为字符串,然后使用String.isEmpty()。isEmpty()仅在length()为0时返回true。(https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty())。

String temp = num + "";
if (temp.isEmpty()) {
    //...
}

或者简单地使用try-catch块,将输入强制转换为新变量。

try {
    month = Integer.parseInt(num);
} catch (NumberFormatException e) {
    // 处理错误
}

请注意,您的变量"Month"应该是"month"。在大多数编程社区中,每个人都使用小写变量。

有无数种处理这种情况的方法,您可以尝试其中的每一种。我希望我列出的那些方法都是正确的。

编辑:
哦,我检查了其他评论,注意到您是初学者。这里可能有一些有用的提示,这样您的班级中的每个人,包括老师,都可以更容易地阅读您的代码。在大多数编程语言中都有类似"checkstyle"的东西。很难解释,但通过一些Google搜索,您可以找到有用的提示。

我将对您的代码提出一些建议,您可以采纳或忽略。比如一些字符之间的空格,一些注释等等。
但不要过于关注代码质量。在一些集成开发环境中,您可以自动将代码格式化为"标准"。在Intellij中,可以使用ctrl+alt+l。

英文:

I hope that I understood your problem correctly.

Your problem is that your user can start the method without a valid argument. If you have a frontend than you should catch it there too. But in the backend (java) you can work with a try-block or simply with if-else.

Cast the Integer to a String and then use regex (maybe something like this

String text = num + "";
if (text != null && text.matches("\\d+")) {
//...
}

Or you can cast your Integer to a String and use String.isEmpty().isEmpty returns true if, and only if, length() is 0. (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty()).

Sting temp = num + "";
if (num.isEmpty()) {
//...
}

Or simply a try-catch Block where you cast your input to a new variable.

try {
Month = Integer.parseInt(num);
} catch (NumberFormatException e) {
// handle error
}

And please notice that your variable "Month" should be "month". In most programming communities everyone uses lowercase variables.

There are countless options how you can handle this situation and you can try every one of them. I hope that the ones I listed are all correct.

Edit:
Oh and I checked the other comments and I noticed that you are a beginner. Here are maybe some useful tips, so everyone in your class including the teacher can read easier your code. In most programming languages there is something like "checkstyle". It is hard to explain, but with some google you can find useful tips.

I will make a few "suggestions" to your code, which you can adopt or ignore. Like spaces between some characters some comments, etc.
But don't focus to hard on the quality. In some IDEs you can automatically format your code to "the standard". With Intellij it is. ctrl+alt+l

import java.util.Calendar;
public class myCalendar {
private Calendar calendar = Calendar.getInstance();
private int day = calendar.get(Calendar.DAY_OF_WEEK);
private int date = this.calendar.get(Calendar.DAY_OF_MONTH);
private int month = calendar.get(Calendar.MONTH) + 1;
private int year = calendar.get(Calendar.YEAR);
/**
* Description what the method does.
*
* @param Year  what does the parameter?
* @param Month ""
* @param Date  ""
*/
public void setCalendar(int Year, int Month, int Date) {
this.calendar.set(Year, Month - 1, Date);
}
public int getDay() {
return day;
}
public int getDate() {
return date;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
/**
* Description what the method does.
*
* @return value (short description)
*/
public int getFirstDay() {
Calendar test = this.calendar;
test.set(year, month - 1, 1);
return test.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
* Description what the method does.
*
* @param num (short description)
* @return (short description)
*/
public int getMonthSize(int num) {
int month;
int days = 0; //My IDE tells me that need to be initialized, but why? Are there cases where the method returns 0?
//I think that num=100 returns 0, so maybe you can catch this case with if(num > 12) or something similar
if (num > 0) {
month = num;
} else {
month = this.month;
}
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
days = 31;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
}
if (month == 2) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
}
return days;
}
public String getNow() {
String monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a = monthNames[month - 1] + ", " + String.valueOf(year);
return a;
}
}

huangapple
  • 本文由 发表于 2020年8月4日 14:49:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63241545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定