By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,536 Members | 1,800 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,536 IT Pros & Developers. It's quick & easy.

Homework help

P: 9
what are the parameters needed in the constructor call below to create a Date variable whose intitial value is the 15th of March 2004????
Aug 23 '06 #1
Share this Question
Share on Google+
32 Replies


P: 9
3 JAVA QUESTIONS THAT I NEED ANSWERING??!?!

Enter the parameters needed in the constructor call below to create a Date variable whose intitial value is the 15th of March 2004.

Date d = new Date( ____________ );
--------------------------------------------------------------------------------

[2] There is a standard class called DateFormat which (among other things) lets you convert dates to various different output formats.

Use it to write a method called convert which converts a Date to a String in the form dd-mmm-yyyy:
public String convert (Date d) {
...
}

For example, when d is a Date variable representing the 25th of December 2006,
String s = convert(d);

should set s to the string "25-Dec-2006".

Enter your answer (just your convert method) below:






--------------------------------------------------------------------------------

[3] Write a condition for the if statement below which will be true when the Date d1 is not later than the Date d2:
if ( ____________________ ) {
...
}
Aug 23 '06 #2

100+
P: 293
D_C
I don't have Java installed anymore, but it may be helpful to look at the Java API for DateFormat. I noticed a method called parse(string s) that may help you with the first question. For number 2, look at the format(Date d, StringBuffer sb, FieldPosition fp) method, and maybe getNumberFormat().

I assume Date(0) is equivalent to midnight Jan 1, 1979, just as the new year began. The time is given in milliseconds, so then every (1000*60*60*24*365.25...=31557600000) is approximately equivalent to a year. There are algorithms to calculate how many days are in between two dates. Finally, if each date is represented as the number of milliseconds then you could simply compare these two numbers that represent the date. I am assuming the less than operator is already implemented for Date.
Aug 23 '06 #3

100+
P: 293
D_C
The easiest thing would be to parse the date, using DateFormat.parse(string source), and let Java do all those calculations so Java figures out a time in ms for you. However, here are the calculations that go on behind the scenes, in case you want to understand.

Leap years
Expand|Select|Wrap|Line Numbers
  1. //int year; bool leap;
  2. if((year % 400) == 0) // If year is divisible by 400
  3.   leap = true;
  4. if((year % 100) == 0) // If year is divisible by 100
  5.   leap = false;
  6. if((year % 4) == 0)   // If year is divisible by 4
  7.   leap  = true;
Calculations
So (26*365 + 6) = 9490+6 =9496 days. // 6 leap years, 1980, 84, 88, 92, 96, 2004, but not 2000.
9496 days * (24 hrs/day) = 227904 hrs.
227904 hrs * (60 min/hr) = 13674240 min.
13674240 min * (60 sec/min) = 820454400 sec.
820454400 sec * (1000ms/sec) = 820454400000 ms.
The 26 years = 820454400000 ms.

We still need to count Jan, Feb, and part of March.
Jan = 31 days, Feb = 28 days (we already counted the leap year since 2000 was not a leap year) and Mar = 15 days.
74 days * 24 hrs/day * 60 min/hr * 60 sec/min * 1000 ms/sec = 6393600000ms.

820454400000 ms + 6393600000 ms = 826848000000 ms.
So, Date(826848000000) should give you Mar, 15, 2004 right at midnight. If you want 4:30 PM, you would have to add
(16hrs(60 min/hr) + 30 min)*60sec/min*1000ms/sec = 59400000 ms.
Then the date would be 826848000000 ms + 59400000 ms = 826907400000 ms, or Date(826907400000).
Aug 23 '06 #4

PLA
P: 44
PLA
Date d = new Date(104, 2, 15);
104 + 1900 = 2004
2 is for March(0 based)
15 for 15 ;-)
But the class Date is deprecated (One of the thing i will nerver understand in Java), you should use the GregorianCalendar instead
Aug 24 '06 #5

PLA
P: 44
PLA
3 JAVA QUESTIONS THAT I NEED ANSWERING??!?!

Enter the parameters needed in the constructor call below to create a Date variable whose intitial value is the 15th of March 2004.

Date d = new Date( ____________ );
--------------------------------------------------------------------------------

[2] There is a standard class called DateFormat which (among other things) lets you convert dates to various different output formats.

Use it to write a method called convert which converts a Date to a String in the form dd-mmm-yyyy:
public String convert (Date d) {
...
}

For example, when d is a Date variable representing the 25th of December 2006,
String s = convert(d);

should set s to the string "25-Dec-2006".

Enter your answer (just your convert method) below:

--------------------------------------------------------------------------------

[3] Write a condition for the if statement below which will be true when the Date d1 is not later than the Date d2:
if ( ____________________ ) {
...
}
[1] See the other post
[2]
GregorianCalendar c = new GregorianCalendar(2006, 11, 25);
Date date = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
result = sdf.format(date);
[3]d1.compareTo(d2) <= 0
Aug 24 '06 #6

P: 9
[1] Given a list of integers and an integer variable declared like this:
List<Integer> list;
int max;

and assuming that some values have been added to the list, write a loop which finds the largest value in list and stores it in max.
--------------------------------------------------------------------------------

[2] A bank account is stored as a Map which maps the names of the account holders to a value representing the current balance of their account:
Map<String,Integer> bank;

Given a String variable declared like this:
String rich = null;

write a loop which will store the name of the person with the most money in their account in rich.

--------------------------------------------------------------------------------

[3] Using the same bank account as in the previous question, and a list of strings:
Map<String,Integer> bank;
List<String> names;

write a loop which fills the list names with the names of all account holders whose accounts are overdrawn, i.e. the balance of their account is less than zero.
------------------------------------------------------------------------------------

[4] Write a method called convertDouble as follows:
public double convertDouble (String value) {
...
}

This method should convert its parameter (a string like "3.1415") to the corresponding value of type double. If the string supplied is not a valid number, it should return 0.0 as its result. Note that you can use the method Double.parseDouble() to do the hard work for you.

Insert your convertDouble method in the space below:

--------------------------------------------------------------------------------

[5] Modify your convertDouble method to ignore any extra characters at the end of the string, so that convertDouble("3.1415xxx") will produce the value 3.1415 as its result.

Insert your convertDouble method in the space below:

--------------------------------------------------------------------------------
[6]
Write a method called countChars which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any IOExceptions which might occur in the method should be passed back to the method's caller.

Insert the code for your method in the space below:


------------------------------------------------------------------------------
[7]
Using the countChars() method from the previous answer, write a method called fileSize() declared as follows:
public int fileSize (String name) {
...
}

which counts the number of characters in the file whose name is supplied as the "name" parameter. This method should return the number of characters in the file, or -1 if an IOException occurs.

Insert the code for your method in the space below:
Aug 24 '06 #7

PLA
P: 44
PLA
I think you don't need a forum but a Java training ;-)

If you are developping a system with money and account, I think you should use BigDecimal (Fix capacity) instead of double (rouding error...)
Aug 24 '06 #8

P: 9
I know i need training, but I need to resolve these questions? can you help please
Aug 24 '06 #9

P: 9
Given a list of integers and an integer variable declared like this:
List<Integer> list;
int max;

and assuming that some values have been added to the list,
What is the loop which finds the largest value in list and stores it in max?
Aug 24 '06 #10

P: 9
thanks 4 the help
Aug 24 '06 #11

PLA
P: 44
PLA
Given a list of integers and an integer variable declared like this:
List<Integer> list;
int max;

and assuming that some values have been added to the list,
What is the loop which finds the largest value in list and stores it in max?
Expand|Select|Wrap|Line Numbers
  1.   public static void main(String[] args)
  2.   {
  3.     List<Integer> list = new LinkedList<Integer>();
  4.     int max = -999;
  5.     list.add(1);
  6.     list.add(12);
  7.     list.add(2);
  8.     list.add(11);
  9.     for (int i : list)
  10.     {
  11.       if (i > max)
  12.       {
  13.         max = i;
  14.       }
  15.     }
  16.     System.out.print("Max is : ");
  17.     System.out.println(max);
  18.   }
  19.  
Aug 24 '06 #12

P: 9
Thank u very much, appreciate that.
Aug 24 '06 #13

P: 9
A bank account is stored as a Map which maps the names of the account holders to a value representing the current balance of their account:
Map<String,Integer> bank;

Given a String variable declared like this:
String rich = null;
How is the loop which will store the name of the person with the most money in their account in rich written?
Aug 24 '06 #14

P: 1
I was given this, can anyone shed some light on it????

How do write a method called countChars which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any IOExceptions which might occur in the method should be passed back to the method's caller.
Aug 24 '06 #15

PLA
P: 44
PLA
A bank account is stored as a Map which maps the names of the account holders to a value representing the current balance of their account:
Map<String,Integer> bank;

Given a String variable declared like this:
String rich = null;
How is the loop which will store the name of the person with the most money in their account in rich written?
Expand|Select|Wrap|Line Numbers
  1. Map<String, Integer> bank = new Hashtable<String, Integer>();
  2. String rich = null;
  3. Integer richBalance = new Integer(0);
  4.  
  5.     bank.put("aaa", new Integer(1020));
  6.     bank.put("bbb", new Integer(2333));
  7.     bank.put("ccc", new Integer(1356));
  8.  
  9.     for (String account : bank.keySet())
  10.     {
  11.       if (bank.get(account) > richBalance)
  12.       {
  13.         rich = account;
  14.         richBalance = bank.get(rich);
  15.       }
  16.     }
  17.     System.out.println("Max is : " + rich + " (" + richBalance + ")");
  18.  
It's my last for that day!
Aug 24 '06 #16

P: 9
Just 1 more! Please
(3rd & Final)

Using the same bank account as in the previous question, and a list of strings:
Map<String,Integer> bank;
List<String> names;

I need to write a loop which fills the list names with the names of all account holders whose accounts are overdrawn, i.e. the balance of their account is less than zero???
Aug 24 '06 #17

PLA
P: 44
PLA
Just 1 more! Please
(3rd & Final)

Using the same bank account as in the previous question, and a list of strings:
Map<String,Integer> bank;
List<String> names;

I need to write a loop which fills the list names with the names of all account holders whose accounts are overdrawn, i.e. the balance of their account is less than zero???
Expand|Select|Wrap|Line Numbers
  1.     Map<String, Integer> bank = new Hashtable<String, Integer>();
  2.     String rich = null;
  3.     Integer richBalance = new Integer(0);
  4.     List<String> names = new LinkedList<String>();
  5.  
  6.     bank.put("aaa", new Integer(1020));
  7.     bank.put("bbb", new Integer(2333));
  8.     bank.put("ccc", new Integer(-1356));
  9.     bank.put("ddd", new Integer(1356));
  10.     bank.put("eee", new Integer(-56));
  11.  
  12.     for (String account : bank.keySet())
  13.     {
  14.       if (bank.get(account) > richBalance)
  15.       {
  16.         rich = account;
  17.         richBalance = bank.get(rich);
  18.       }
  19.       if (bank.get(account) < 0)
  20.       {
  21.         names.add(account);
  22.       }
  23.     }
  24.     System.out.println("Max is : " + rich + " (" + richBalance + ")");
  25.     System.out.println("Names are : " + names);
  26.  
It is easy as you can see !!!
Aug 24 '06 #18

PLA
P: 44
PLA
In fact it is the first time I use Generics in Java (I remembered ugly code and response time in C++ with templates) and it's quite good. Thanks for the lesson
Aug 24 '06 #19

100+
P: 293
D_C
I don't know how list is defined, but this may give you an idea of how to do it. I am assuming there are list.length() elements in the list, and list.entry(i) returns the ith element. Similarly for map. I will give you an idea for #2, and some suggestions for the others.

Number 2
Expand|Select|Wrap|Line Numbers
  1. max = map.entry(0).getInt(); // since list is not empty.
  2. for(int i = 0; i < map.length(); i++)
  3. {
  4.    if(max < map.entry(i).getInt())
  5.    {
  6.       max = map.entry(i).getInt());
  7.       rich = map.entry(i).getStr());
  8.    }
  9. }
#1. Just like #2, only you don't worry about the string rich. Also it's a list instead of a map.
#3. Change the if statement. It's condition is given to you. The code to execute should simply put the person's name into a list.

The others seem just as trivial. Give it a go yourself, and if you have any trouble, post your code, what's wrong with it, and what you can't figure out. Then we'll look at it and see.
Aug 24 '06 #20

100+
P: 293
D_C
Java API for BufferedInputStream. Become friends with the Java API. I don't have Java to test this, but it should work. Also, by not catching the exception, it is returned as requested.
Expand|Select|Wrap|Line Numbers
  1. public int countChars(InputStream is) throws IOException
  2. {
  3.    int count = 0;
  4.    BufferedInputStream bis = new BufferedInputStream(is);
  5.    while(bis.read() != -1) // -1 is returned when end of input is reached.
  6.    {
  7.       count++;
  8.    }
  9.    return count;
  10. }
Aug 24 '06 #21

PLA
P: 44
PLA
I don't know how list is defined, but this may give you an idea of how to do it. I am assuming there are list.length() elements in the list, and list.entry(i) returns the ith element. Similarly for map. I will give you an idea for #2, and some suggestions for the others.

Number 2
Expand|Select|Wrap|Line Numbers
  1. max = map.entry(0).getInt(); // since list is not empty.
  2. for(int i = 0; i < map.length(); i++)
  3. {
  4.    if(max < map.entry(i).getInt())
  5.    {
  6.       max = map.entry(i).getInt());
  7.       rich = map.entry(i).getStr());
  8.    }
  9. }
#1. Just like #2, only you don't worry about the string rich. Also it's a list instead of a map.
#3. Change the if statement. It's condition is given to you. The code to execute should simply put the person's name into a list.

The others seem just as trivial. Give it a go yourself, and if you have any trouble, post your code, what's wrong with it, and what you can't figure out. Then we'll look at it and see.
An other way is to use Java 5.0 Generics and loop
Other thread
Aug 25 '06 #22

Expert Mod 100+
P: 2,327
All of jaime's questions got merged into one homework help thread.
Aug 26 '06 #23

P: 1
I need some help on this. I did this code but now need to be updated. I really dont understand what are the benefit. How do I do? Thank you so much for any help.
Ruth


I have the code below how do I do to update the new method:

int count = ((Integer)(orderMap.get(key))).intValue();
currentOrder.put(unknownItem, new Integer(count));


That is the code to be updated.


public class ToysInventory {
private String[] toysOrdered = {"bear", "train", "car", "ball", "doll",
"ball", "train", "doll", "game", "train",
"bear", "doll", "train","car", "ball",
"bat", "glove", "bat", "b", "doll", "bear",
"ball", "doll", "bat", "car", "glove",
"train", "doll", "bear" };

private String[] toysInventoryList = {"ball", "bat", "bear", "car", "doll",
"game", "glove", "playstation", "train" };

private int InventoryCounter[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

public static void main(String[] args) {//BEGIN main()

ToysInventory toys = new ToysInventory();
toys.countToys();
System.exit(0);
}//END main()

private void countToys() {
int temp = 0;
int orderedIndex = 0;
int inventoryIndex = 0;

for (inventoryIndex = 0; inventoryIndex < toysInventoryList.length; inventoryIndex++){
for (orderedIndex = 0; orderedIndex < toysOrdered.length; orderedIndex++) {
if (toysOrdered[orderedIndex] == toysInventoryList[inventoryIndex]) {
temp = temp + 1;
}//END if
InventoryCounter[inventoryIndex] = temp;
}
temp = 0; //reset counter value
}

System.out.println("[order status]");
for (temp = 0; temp < InventoryCounter.length; temp++){
// (*) before any item for which the customer has requested
// a quantity of 5 or more.
if (InventoryCounter[temp] >= 5){
System.out.print("*");
}
else {
System.out.print(" ");
}
System.out.println(toysOrdered[temp] + " = " + InventoryCounter[temp]);
}
}//END countToys()

}//END ToysInventory
Sep 4 '06 #24

P: 2
for question
Given a list of integers and an integer variable declared like this:

List<Integer> list;
int max;

and assuming that some values have been added to the list, write a loop which finds the largest value in list and stores it in max.

i used this answer
for (int i : list)
{
if (i > max)
{
max = i;
}
}
System.out.println(max);
}
and i get these errors
Main.java:36: illegal start of type
for (Integer n : list) {
^
Main.java:48: <identifier> expected
}
^
Main.java:49: 'class' or 'interface' expected
}
^
Main.java:49: 'class' or 'interface' expected
}
^
4 errors

any ideas in what im doing wrong?
Mar 6 '08 #25

satch
P: 23
for question
Given a list of integers and an integer variable declared like this:

List<Integer> list;
int max;

and assuming that some values have been added to the list, write a loop which finds the largest value in list and stores it in max.

i used this answer
for (int i : list)
{
if (i > max)
{
max = i;
}
}
System.out.println(max);
}
and i get these errors
Main.java:36: illegal start of type
for (Integer n : list) {
^
Main.java:48: <identifier> expected
}
^
Main.java:49: 'class' or 'interface' expected
}
^
Main.java:49: 'class' or 'interface' expected
}
^
4 errors

any ideas in what im doing wrong?
Hey joej231,
I think it would have been helpful if you had posted the complete code because without the code the errors are of no help.
Anyways the following code finds the max given a list of numbers(that is what you are trying to do..right?). Hope it solves your problem.
[ no code spoonfeeding alllowed -- mod ]

First of all, joej should've started his/her own thread for the problem and not hijack
a years old thread. Second, we don't spoonfeed source code.

kind regards,

Jos
Mar 6 '08 #26

MonaLisaO
P: 13
[ no code spoonfeeding alllowed -- mod ]

First of all, joej should've started his/her own thread for the problem and not hijack
a years old thread. Second, we don't spoonfeed source code.

kind regards,

Jos
I'm confused, is this the real JosAH or someone who is saying some thing that JosAH would say? Because I think also he would have said be sure to use CODE tags.

~mona
Mar 6 '08 #27

Expert 10K+
P: 11,448
I'm confused, is this the real JosAH or someone who is saying some thing that JosAH would say? Because I think also he would have said be sure to use CODE tags.

~mona
I almost never say that, I simply insert those tags myself and add an 'edit' line ;-)

kind regards,

Jos ( and don't forget the CODE tags folks! ;-)
Mar 6 '08 #28

MonaLisaO
P: 13
I almost never say that, I simply insert those tags myself and add an 'edit' line ;-)

kind regards,

Jos ( and don't forget the CODE tags folks! ;-)
But apparently not in this case? lol

~mona
Mar 6 '08 #29

satch
P: 23
[ no code spoonfeeding alllowed -- mod ]

First of all, joej should've started his/her own thread for the problem and not hijack
a years old thread. Second, we don't spoonfeed source code.

kind regards,

Jos
Point noted :)
I had read about not spoonfeeding source code on the forum but I felt he had written most of the logic correctly and was probably making a mistake in initialization/syntax, so I posted the code.
Anyways from now on I'll avoid posting code.
Mar 7 '08 #30

P: 14
Using the countChars() method from the previous answer, write a method called fileSize() declared as follows:
public int fileSize (String name) {
...
}
which counts the number of characters in the file whose name is supplied as the "name" parameter. This method should return the number of characters in the file, or -1 if an IOException occurs.

This is what i have done :
public int fileSize(String name) throws IOException
{
try{
int count = 0;
File file = new File("name");
Scanner scan = new Scanner(file);

while( file.exists())
{
count++;
}
return count;
}
catch (IOException e) {
return -1;
}
}

error: cannot find the class scanner.
Any suggestions would be much appreciated?
Mar 24 '08 #31

Expert 100+
P: 849
As much as I hate to implicitly condone thread necromancy, did you import java.util.Scanner?
Mar 25 '08 #32

P: 14
same question ..
public int fileSize(String name) throws IOException
{ try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("name"));
int charLength = 0;
int c;
while ((c = isr.read()) != -1)


charLength++;

return(charLength);
}

catch (Exception e) {
return -1;
}

}


error : Test 1 succeeded (0 marks):
The compilation was successful


Test 2 failed (exit code = 1):
The output should have been:
countChars

This is what was actually produced:
public int fileSize(String name) throws IOException
{ try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("name"));
int charLength = 0;
int c;
while ((c = isr.read()) != -1)


charLength++;

return(charLength);
}

catch (Exception e) {
return -1;
}

}


Test 3 failed (exit code = 1):
Your converted value was -1
It should have been 1446
Try again!


Test 4 failed (exit code = 1):
Your converted value was -1
It should have been 414
Try again!


Test 5 succeeded (1 mark):
Success!

help??
Mar 25 '08 #33

Post your reply

Sign in to post your reply or Sign up for a free account.