Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Exception to set variables

Posted on 2011-10-06
10
Medium Priority
?
232 Views
Last Modified: 2012-05-12
This class can have the following arguments:

> java PrintCalendar 5 2010    <-- is supposed to set month= 5 and year = 2010

> java PrintCalendar 5            <-- is supposed to set month= 5 and year = current year

> java PrintCalendar              <-- no arguments is supposed to set month= current month and year = current year

Also arguments like

> java PrintCalendar 5 2010 44 and
> java PrintCalendar 5 xy

is to throw exceptions.

I have a partial code and want to shape up to the the above.

Thank you

import java.util.Scanner;

public class PrintCalendar {
    
   static int year;
   static int month;

   public static void validateInput(String s) 
           throws NumberFormatException, WrongNumberOfInputsException {

        String[] inputs = s.split(" ");

        try {
            if(inputs.length > 2)
                throw new WrongNumberOfInputsException("You need to enter month year (ex. 2 2010)\n");
            
            year=Integer.parseInt(inputs[1]); //if empty take current year
            month=Integer.parseInt(inputs[0]); //if year and month both empty take current month
                    
        }
        catch(NumberFormatException ex){
            throw ex;
        }
   }    
   
    public static void main(String[] args) {
        
        Scanner input=new Scanner(System.in);
        String str=input.nextLine();
        validateInput(str);
        
        System.out.print(month + " " + year); 
        //printMonth();
    }

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 4
  • 3
  • 3
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927298
Personally i would just validate the args to main to begin with
if (args.length > 2) {
    usage();
}

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36927326
re:>

if (args.length > 2) {
    usage();
}

where you include the message it is suppose to show?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927363
In the method 'usage'. Once you've done that, you can rely on the exceptions from Calendar, or other api classes:
Calendar c = Calendar.getInstance();
c.setLenient(false);
c.set(Calendar.MONTH, Integer.parseInt("13")); // exception
c.set(Calendar.YEAR, Integer.parseInt("foo")); // NFE

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36927420
also in line 30 "validateInput(str);" i was getting error I winder if you could also take look at it.

thanks
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36927508
Maybe you can use some method like this - not tested yet though

import java.text.SimpleDateFormat;

public class PrintCalendar {

    static SimpleDateFormat sdfy = new SimpleDateFormat("yyyy");
       static SimpleDateFormat sdfm = new SimpleDateFormat("MM");


   public static String getDateString(String [] ss) throws WrongNumberOfInputsException {

       String month = "";
        String year = "";
       java.util.Date dd = new java.util.Date();



          if(ss.length > 2)throw new   WrongNumberOfInputsException (" too many arguments");
         else  if(ss.length == 2){
              int m = -1;
              int y = -1;
              try {
                m = Integer.parseInt(ss[0]);
                y = Integer.parseInt(ss[1]);
             }  catch(Exception ex){

              }
            if( m < 1 || m > 12 || y < 1900 || y > 2100)throw  new   WrongNumberOfInputsException (" wrong year or month");
              year = ss[1];
              month = ss[0];

          }   else if (ss.length == 1){
              int m = -1;
               try {
                m = Integer.parseInt(ss[0]);

             }  catch(Exception ex){

              }
               if( m<1 || m >12)throw  new   WrongNumberOfInputsException (" wrong year or month");

              month = ss[0];
              year = sdfy.format(dd);
          }  else if (ss.length == 0){
              month = sdfm.format(dd);
              year = sdfy.format(dd);

          }

         return (month + "-" + year);
   }

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

           try{
               dateString = getDateString(args);
           }  catch(Exception ex){
               System.out.println(ex);
               System.out.println("usage");
               System.exit(0);

           }


    }

}

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36927534
I tested  - it works

import java.text.SimpleDateFormat;

public class PrintCalendar {

    static SimpleDateFormat sdfy = new SimpleDateFormat("yyyy");
       static SimpleDateFormat sdfm = new SimpleDateFormat("MM");


   public static String getDateString(String [] ss) throws WrongNumberOfInputsException {

       String month = "";
        String year = "";
       java.util.Date dd = new java.util.Date();



          if(ss.length > 2)throw new   WrongNumberOfInputsException (" too many arguments");
         else  if(ss.length == 2){
              int m = -1;
              int y = -1;
              try {
                m = Integer.parseInt(ss[0]);
                y = Integer.parseInt(ss[1]);
             }  catch(Exception ex){

              }
            if( m < 1 || m > 12 || y < 1900 || y > 2100)throw  new   WrongNumberOfInputsException (" wrong year or month");
              year = ss[1];
              month = ss[0];
              while(month.length() < 2)month = "0" + month;

          }   else if (ss.length == 1){
              int m = -1;
               try {
                m = Integer.parseInt(ss[0]);

             }  catch(Exception ex){

              }
               if( m<1 || m >12)throw  new   WrongNumberOfInputsException (" wrong year or month");

              month = ss[0];
                while(month.length() < 2)month = "0" + month;
              year = sdfy.format(dd);
          }  else if (ss.length == 0){
              month = sdfm.format(dd);
              year = sdfy.format(dd);

          }

         return (month + "-" + year);
   }

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

           try{
               dateString = getDateString(args);
           }  catch(Exception ex){
               System.out.println(ex);
               System.out.println("usage");
               System.exit(0);

           }

        System.out.println(dateString);


    }

}

Open in new window


java PrintCalendar 5 2010 abs

ouput:
 too many arguments
usage

Open in new window

0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36927988
thanks,

brb
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36928008
Very nice. Thank you thank you.

I am trying to understand your masterful code now. I possible, please ad some comments to it to help me understand the process.

Thank you,

Mike
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36928181
Waht part you don't unsderstand,  I think we already went through throwing exceptions etc.
It jsut checks if there are too many then Thrrows eexception
If there are two - it checks some reasonable conditions
about values and so thaey ar integers and throws exception with another message if it is not
if there is one - we check as before but only the month and if there are no
arguments - then nothing to check
then it uses SimpleDateFormat to format the month and year of today's date if necessary.

and in the main we justc call it to get the string and catch Exception
in case there is a problem.

let me know what other things cause questions
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36930278
As i mentioned, your code would be a lot cleaner and simpler if you used Calendar
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month14 days, 11 hours left to enroll

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question