Passing a string array in a main method - java

I have homework where I have to write a small program that asks for a number and returns the month assigned to that number.
So far I have written two different classes, one to prompt the user for int, and the other with the arrays of month. Now my problem is to pass over the months to the main class when the user enters a number.
So far for the main class I have this and I have no idea on how to proceed...
I get:
java:17: error: array required, but Date found System.out.println(monthName[index]);
I tried to be as detailed as possible.
import java.util.Scanner;
public class Driver {
public static void main(String[] args)
{
Utility input = new Utility();
final int MONTH_NAMES = 12;
int[] month = new int[MONTH_NAMES];
Date monthName = new Date();
{
System.out.println(input.queryForInt("Enter the number for a month ")) ;
}
for (int index = 0; index < 12; index++)
System.out.println(monthName[index]);
}
}

Your System.out line is not referencing the array you named month.

I don't think you intended to use Date monthName here
System.out.println(monthName[index]);
Judging by the number of indexes your for loop is counting, it looks like you wanted to use int[] month.
System.out.println(month[index]);

mouthName is a Date object, not an array. Also, why use a for loop to print out a whole year's mouth?
I think it can change the last for loop to System.out.printLn(mouthName.getMouth()) if the input.queryForIntmethod can successfully pass the int mouth to the mouthName object.

Related

how to get user input (args) and pass it to a collection taking method

I've found an open source Java code that does IRR calculation. I would like to integrate this into my program. The idea is to input this java program some amounts and dates it then calculates IRR and returns a single number (double). The program excepts collection class as input (combination of numbers and dates) then returns the number. It can take as many number and dates as user wants. There are some sample code within the documentation, but all of them shows how this program gets parameters within the code hard coded. I'm trying to change it, so the program will get user input parse it into numbers and dates then ideally converts them into collection and pass it to the java program . I couldn't do it. I couldn't create collection object from user input and passed it to the program. I'm attaching sample code that does it values hardcodeded in the code, all I want to write a class that will dynamically capture user input (combination value and date, ideally one value, one date and so on) and pass it to the XIRR method.
public double xirr_issue5b() {
double rate = new Xirr(
new Transaction(-2610, "2001-06-22"),
new Transaction(-2589, "2001-07-03"),
new Transaction(-5110, "2001-07-05"),
new Transaction(-2550, "2001-07-06"),
new Transaction(-5086, "2001-07-09"),
new Transaction(-2561, "2001-07-10"),
new Transaction(-5040, "2001-07-12"),
new Transaction(-2552, "2001-07-13"),
new Transaction(-2530, "2001-07-16"),
new Transaction(-9840, "2001-07-17"),
new Transaction(38900, "2001-07-18")
).xirr();
return rate;
}
One thing to note is that the XIRR implementation in the open source package you refer to has public Xirr(Transaction... tx){ which (if you are not familiar with var args) means you can have any number of elements of transactions. What it also allows is for you to enter in an array. XIRR also can take in Collections (such as ArrayLists) So what I do in the following code is:
create a Scanner to read in the user input
Create a date formatter to convert the strings to dates
create an ArrayList that holds the transactions
An iteration counter based on user input
A for loop that loops the iterations amount predefined by the user and adds a new Transaction to the ArrayList each iteration taking in the user's next int and next String (converted to a date via date formatter).
I feed the ArrayList into the Xirr method.
Try this:
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.Scanner;
public double xirr_issue5b() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Scanner sc = new Scanner(System.in);
ArrayList<Transaction> trans = new ArrayList<Transaction>();
int iterations = sc.nextInt();
for(int k = 0; k < iterations; k++) {
trans.add(new Transaction(sc.nextInt(), format.parse(sc.next())));
}
double rate = Xirr(trans).xirr();
sc.close();
return rate;
}

Generating Random Date

I'm a novice Java student. I have only been studying programming for a few months at school, and so I am currently pretty bad at it, and often feel stuck doing my assignments.
Anyway, I have a question regarding an assignment. I have been looking around and not quite finding the answers I need, so I was hoping to find some help on here. It would be much appreciated. My assignment goes like this: "Write a program that creates a Date object and a Random object. Use the Random object to set the elapsed time of the Date object in a loop to 10 long values between 0 and 100000000000 and display the random longs and the corresponding date and time."
We were just introduced to the classes java.util.Random and java.util.Date to work with this assignment, and are expected to use them to create the needed Date and Random objects.
The only things I really know how to do for this assignment are how to start the code:
public class RanDate {
public static void main(String[] args) {
And how to create the loop:
for (int i = 0; i <= 10; i++) {
I'm sorry if my question was too vague, or if I didn't ask something properly. This is my first time asking for help on this site. Thank you in advance for your help.
How about this?
Random rnd = new Random();
Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextLong()));
System.out.println(date.toString());
Just subtract the actual time System.currentTimeMillis() and random generated long number with rnd.nextLong(). It's better finally wrap it all to Math.abs().
Try this code.
I think the assignment asks for the long to be the value in the date object, but I'm not shure.
public static void main(String[] args) {
Long max =0L;
Long min =100000000000L;
//Use the date format that best suites you
SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i <= 10; i++) {
Random r = new Random();
Long randomLong=(r.nextLong() % (max - min)) + min;
Date dt =new Date(randomLong);
System.out.println("Generated Long:"+ randomLong);
System.out.println("Date generated from long: "+spf.format(dt));
}
}
Sample Output:
Generated Long:68625461379
Date generated from long: 05/03/1972

How to create a consecutive number by month

I'm create a java webapp and I have to create a consecutive number that should starts every month. The idea is to have something like this:
01-0414 / 02-0414 /03-0414 / 04-0414
where the first two digits should be the consecutive number, and the last four digits are the month and year.
I'm using spring 3.2.2 and hibernate 4.2.6. I really appreciate any help about this.
thanks
Well, your question is not clear. But as far as I understand you need help to get the date. You can use Calendar() or Date(), use something like this Calendar.get(Calendar.MONTH)to get the month and year (or simply parse to string and substring where you want).
Regarding the number at the beginning, I will assume (again, since you are not clear) that it is passed as an input. So basically you concatenate that with the "-" and the output of the previous step; the date thingy.
I hope I helped!
If you want to encode your web app string using a sequence number that gets reset to 1 at the beginning of each month, you could use a singleton class instance to hold the month and sequence number state. The code string generator method checks whether the month has changed, and if so, it resets the internal current month to the new month, and resets the effective internal sequence number to 1.
Here is the generator class (see below for an example of how to use it):
public class MySequenceCodeStringGenerator {
private static final int generatorMonth;
private static final int generatorSequenceNumber;
// Create a singleton instance to hold month and sequence number state.
private static final MySequenceCodeStringGenerator INSTANCE = new MySequenceCodeStringGenerator();
private MySequenceCodeStringGenerator() {
generatorMonth = getCurrentMonth();
generatorSequenceNumber = 0;
}
/////////////////////////
// PUBLIC functions:
/////////////////////////
// Get the singleton instance:
public static MySequenceCodeStringGenerator getInstance() {
return INSTANCE;
}
// Get the formatted sequence code string:
public static int getSequenceCodeString {
int sequenceNumber = getSequenceNumber();
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
String yearString = String.valueOf(year);
return String.format( "%02d-%02d%s", sequenceNumber, month+1, yearString.substring(2) );
}
// Get the current month:
private int getCurrentMonth() {
Calendar now = Calendar.getInstance();
return now.get(Calendar.MONTH);
}
// Get the singleton sequence number. Update if this is a new month.
private int getSequenceNumber() {
currentMonth = getCurrentMonth();
if ( currentMonth != generatorMonth ) {
generatorMonth = currentMonth;
generatorSequenceNumber = 0;
}
return ++generatorSequenceNumber;
}
}
Here's an example of how you use the generator class:
String myWebAppString = MySequenceCodeStringGenerator.getInstance().getSequenceCodeString();

How to generate series of ascending number that include date element?

Hello. I want to create a function that generates ascending numbers.
For example, if today's date is June 21st, 2013 then the numbers will be 130621001.
The last three digits are ascending numbers, and it'll reset back to 001 on each date.
I can figure out on how to make the date digits, but I'm stuck with those last three digits.
Thank you in advance.
try this, good luck
public static String NextNumber(String currentNumber) {
//assume yymmddnnn
String sDateNum = currentNumber.substring(0, 6);
String sCurrentNum = currentNumber.substring(6,9);
int i = Integer.valueOf("1" + sCurrentNum);
i++;
return sDateNum + String.valueOf(i).substring(1, 4);
}
System.out.println(NextNumber("130621001"));
The real question is how you know what your previous answer was.
today = myDateFormatter(System.currentTimeMillis());
if (today.equals(oldDay)) count++;
else count == 0;
oldDay = today;
If this is a long running process, oldDay and count can be simple fields in your class. If the process exits and restarts, you will need to get your old answers from somewhere and set them to the largest value.

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources