When I run the following code I receive the error -
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at homework6.main(homework6.java:6)
I researched why this could occur and previous answers had said the class name needed to match the java file name, my class matches that of the .java file as well. I also tried removing "void" and the entire statement altogether, but then a new error occurred saying I needed public void main(String[] args). Am I encountering a different problem then the class and .java?
public class homework6 {
public static void main(String[] args) {
class Date {
private int month;
private int day;
private int year;
private String name;
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
public Date(int m, int d, int y) {
setDate(m, d, y);
}
public void setDate(int m, int d, int y) {
month = m;
day = d;
year = y;
if (m ==1 )
name="January";
else if(m == 2)
name="February";
else if(m == 3)
name="March";
else if(m == 4)
name="April";
else if(m == 5)
name = "May";
else if(m == 6)
name = "June";
else if(m == 7)
name = "July";
else if(m == 8)
name = "August";
else if(m == 9)
name = "September";
else if(m == 10)
name = "October";
else if(m == 11)
name="November";
else if(m == 12)
name = "December";
}
public void showDate1() {
System.out.println(month + "/" + day + "/" + year);
}
public void showDate2() {
System.out.println(name + "" + day + "," + year);
}
public void showDate3() {
System.out.println(day + "" + name + "" + year);
}
}
}
}
You're nesting a class, Date, within a method, the main method to be precise -- something you can't and shouldn't do.
Solution: don't do this.
Create one file called Date.java and place your Date class code in it.
Create a 2nd file called Homework6.java and place your main method in it.
Done.
Valid points those in the answer. You could alternatively just put the class outside the main and get it to compile.
If you take a step back though, and assuming you get this code to compile, what would be the expected output? You seem to make no calls to any methods. Do you want to spend a moment in understanding your logic?
Probably because of this:
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
The first two brackets should be removed, because the code between the second two is not in a method. So it should be like this:
public Date() {
month=1;
day = 1;
year = 2001;
name = "January";
}
Related
I'm trying to make a casino program for my school project. Everything seems to work just fine except that the statement of the do-while loop inside the main() method is always skipped at the first, third, fifth (odd) lines in the console.
THE PROGRAM:
import java.util.Scanner;
import java.text.*;
import java.util.*;
public class Casino
{
public static Scanner input;
static final String SEPARATOR = "\n";
public static void main (String[] args) throws Exception
{
int winnings;
while (getBet() != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * getBet();
display(thePull, winnings);
}
System.out.println("Thanks");
}
//gets bet, stores in static class variables
public static int getBet()
{
final double MAX_BET = 50;
String prompt, strUserResponse;
int intResponse;
input = new Scanner(System.in);
do
{
prompt = "How much would you like to bet ( Min $1 - Max $50 ) "
+ "or press '0' to quit?";
System.out.print(prompt);
strUserResponse = input.nextLine();
intResponse = Integer.parseInt(strUserResponse);
}
while( intResponse < 0 || intResponse > MAX_BET );
return intResponse;
}
public static String randString()
{
int bar = 38;
int cherries = 78;
int space = 85;
int seven = 100;
String randomString = "";
int randomNum = 1 + (int)(Math.random() * 100);
if (randomNum <= bar)
randomString = "BAR";
else if (randomNum <= cherries)
randomString = "cherries";
else if (randomNum <= space)
randomString = "space";
else if (randomNum <= seven)
randomString = "7";
return randomString;
}
public static TripleString pull()
{
TripleString pullString = new TripleString();
String str1 = randString();
pullString.setString1(str1);
String str2 = randString();
pullString.setString2(str2);
String str3 = randString();
pullString.setString3(str3);
return pullString;
}
public static int getPayMultiplier (TripleString thePull)
{
if (thePull.getString1() == "cherries" &&
thePull.getString2() != "cherries" )
return 5;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() != "cherries")
return 15;
else if (thePull.getString1() == "cherries" &&
thePull.getString2() == "cherries" &&
thePull.getString3() == "cherries")
return 30;
else if (thePull.getString1() == "BAR" &&
thePull.getString2() == "BAR" &&
thePull.getString3() == "BAR")
return 50;
else if (thePull.getString1() == "7" &&
thePull.getString2() == "7" &&
thePull.getString3() == "7")
return 100;
else
return 0;
}
public static void display (TripleString thePull, int winnings)
{
System.out.println(SEPARATOR + ">>>Brrrrrr! Your Pull Is . . .<<<"
+ SEPARATOR + thePull.toString());
if ( winnings == 0)
System.out.println("Sorry you lose. . . GOOD LUCK NEXT TIME!"
+ SEPARATOR);
else
System.out.println("Congaratulations, you win =" + " $" + winnings
+ " !" + SEPARATOR + "YEAY !!! :):):)" + SEPARATOR);
}
}
class TripleString
{
//member data
private String string1, string2, string3;
//static constants
public static final double MIN_LEN = 1;
public static final double MAX_LEN = 50;
public static final String DEFAULT_STRING = "undefined";
//default constructor
TripleString ()
{
string1 = DEFAULT_STRING;
string2 = DEFAULT_STRING;
string3 = DEFAULT_STRING;
}
//parameter-taking constructor
TripleString (String str1, String str2, String str3)
{
if (! setString1(str1))
str1 = DEFAULT_STRING;
if (! setString2(str2))
str2 = DEFAULT_STRING;
if (! setString3(str3))
str3 = DEFAULT_STRING;
}
//private static helper method
private boolean validString(String str)
{
if (str == null || str.length() < MIN_LEN || str.length() > MAX_LEN)
return false;
else
return true;
}
//accessor set methods
public boolean setString1 (String stringName1)
{
if ( !validString(stringName1) )
return false;
string1 = stringName1;
return true;
}
public boolean setString2 (String stringName2)
{
if ( !validString(stringName2) )
return false;
string2 = stringName2;
return true;
}
public boolean setString3 (String stringName3)
{
if ( !validString(stringName3) )
return false;
string3 = stringName3;
return true;
}
//accessor get methods
public String getString1 () { return string1; }
public String getString2 () { return string2; }
public String getString3 () { return string3; }
public String toString ()
{
String reStr;
reStr = string1 + " "+ string2 + " " + string3;
return reStr;
}
}
Here is the example of my run:
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?6
//Brrrrr below supposed to have ">>>" "<<<" but I remove it manually in this example since it creates blockquotes
Brrrrrr! Your Pull Is . . .
cherries cherries BAR
Congaratulations, you win = $90 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?7
Brrrrrr! Your Pull Is . . .
7 BAR cherries
Sorry you lose. . . GOOD LUCK NEXT TIME!
I want to make it looks more like
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?1
Brrrrrr! Your Pull Is . . .<<<
BAR BAR BAR
Congaratulations, you win = $50 !
YEAY !!! :):):)
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?2
Brrrrrr! Your Pull Is . . .<<<
BAR cherries BAR
Sorry you lose. . . GOOD LUCK NEXT TIME!
How much would you like to bet ( Min $1 - Max $50 ) or press '0' to quit?0
I think the problem has to be related with the loop in my getInput() method, but I'm really not sure why. I know I could've not make a loop in the getInput() method, but my instructor specifies that the method has to loop until the user put the valid #(1-50)
I've tried changing it to the standard while loop or modifying the code in many other way, but in new ways come new problems. For example, if I change my main method to
Alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
while (getBet() != 0);
System.out.println("Thanks");
}
If I use the above code for the main, my variable bet will stay the same for every loop since it has been initiated before that.
Edit: the alternate main() method
Edit2: Add more sample run
Your second main does not work, because you do not re-assign the bet variable.
Working simple alternate main()
public static void main (String[] args) throws Exception
{
int bet = getBet(), winnings;
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
bet = getBet();
}
while ( bet != 0);
System.out.println("Thanks");
}
Your first main does not work because you call getBet() twice
Working main
public static void main (String[] args) throws Exception
{
int winnings;
int bet;
while ((bet = getBet()) != 0)
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = getPayMultiplier(thePull) * bet;
display(thePull, winnings);
}
System.out.println("Thanks");
}
If you want your bet variable to not remain the same, you can change the while loop to simply:
while(true){
//get the bet here
if(bet == 0){
break;
}
//Do the rest of your stuff here.
}
This will change the bet every iteration but still stop running if it is zero.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have class date which just simply creates an arrayList of days of the week.
import java.util.*;
public class Date {
public static final String[] daysofTheWeek = {"Mon" , "Tue" , "Wed" , "Thurs" , "Fri" , "Sat" , "Sun"};
private String dayofweek;
private int day;
private int month;
public int getDate() {
return this.day;
}
public int getMonth() {
return this.month;
}
public Date(String dayofweek, int day, int month) {
this.day = 1;
if (day >= 1 && day <= 31) {
this.day = day;
}
this.month = 12;
if (month >= 1 && month <= 12) {
this.month = month;
}
this.dayofweek = "Mon";
if (isValidDOW(dayofweek)) { // why is this in the parameters?
this.dayofweek = dayofweek;
}
}
// must validate is DOW
// TRUE/FALSE is the day of the week matching?
public boolean isValidDOW(String d) {
for (int i = 0; i < dayofweek.length(); i++)
if (d.equals(daysofTheWeek[i])) { // why i?
return true;
}
return false;
}
// to string
public static String monthToString(int i) {
switch(i) {
case 1: return "January";
case 2: return "Feb";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid Month!!";
}
}
public String toString() {
return this.dayofweek + "," + Date.monthToString(this.month) + " " + this.day;
}
public String getDayOfWeek() {
return this.dayofweek;
}
}
Now I am trying to get all days ( Say, return number of times sundays pop up). I tried using a loop to go through and count everything, but I am getting a null pointer exception. I've been looking at this for a while, and can't figure out whats wrong with it. Can anyone guide me in the right direction?
import java.util.*;
/**
* ArrayList example
*/
public class Calendar {
private ArrayList<Date> Schedule;
public ArrayList<Date> sundays(String dayofweek) {
ArrayList<Date> app = new ArrayList<Date>();
for (Date entry : Schedule) {
String d = entry.getDayOfWeek();
if (entry.getDayOfWeek() == dayofweek) {
app.add(entry);
}
else if (app.size() == 0) {
return null;
}
}
return app;
}
}
You never initialize the field Schedule, so it is default-initialized to null. Therefore, the line for (Date entry:Schedule) (which is syntactic sugar for calling Schedule.iterator() and iterating over the resulting iterator) throws a NullPointerException.
Also — non-static field names in Java are supposed to start with lowercase letters. You should change Schedule to schedule. (Or you can follow one of the more-specific naming conventions that exist out there. Some projects start all field-names with f — in your case fSchedule; others start all field-names with m for "member" — in your case, mSchedule. If you adopt one of those conventions, just be sure to be consistent about it.)
I think the method isValidDOW should be:
public boolean isValidDOW(String d){
for (int i=0; i < daysofTheWeek.length; i++)
if ( d.equals(daysofTheWeek[i])) // why i?
{
return true;
}
return false;
}
Using daysofTheWeek.length instead of dayofweek.length(), for example if dayofweek = 'Sat', the for loop will only execute 3 times, but 'Sat' is in the 6th place and the value is 5 in ArrayList daysofTheWeek.
I am trying to figure out how to write a constructor that calls methods. I have been given the following instructions for a Java project. The emboldened ones are relevant to this step. Step 3 I have completed, but I can't confirm if I completed it correctly. The code for Step 3 is the second Date constructor within the Date class.
Uncomment line 1 from DateTest (don’t forget to delete the “Line 1.” part) and build and run the project. What is the output? Why is this the output?
Create a default constructor for Date which sets the date to 1/1/2000. Build and run the project. What is the output?
Create a constructor that has three int parameters for the month, day, and year and sets the values of these instance variables to the values passed in. Uncomment lines 2 and 3. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls setMonth(), setDay(), and setYear(). Build and run the project. What is the output?
Write a set() method that has three parameters for the month, day, and year. Uncomment lines 4 and 5. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls set (). Build and run the project. What is the output?
Below is the code for Date class and DateTest class.
package datetest;
import java.util.Scanner;
public class Date
{
public Date() {
month = 1;
day = 1;
year = 2000;
}
public Date(int m, int d, int y) {
month = m;
day = d;
year = y;
}
private int month;
private int day;
private int year; //a four digit number.
public void setYear(int newYear)
{
year = newYear;
}
public void setMonth(int newMonth)
{
if ((newMonth <= 0) || (newMonth > 12))
{
month=newMonth;
}
else
month = newMonth;
}
public void setDay(int newDay)
{
if ((newDay <= 0) || (newDay > 31))
{
day=1;
}
else
day = newDay;
}
public int getMonth( )
{
return month;
}
public int getDay( )
{
return day;
}
public int getYear( )
{
return year;
}
public void printDate( )
{
System.out.print(getMonth() + "/" + getDay() + "/" + getYear());
}
public void readInput( )
{
boolean tryAgain = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter month, day, and year.");
System.out.println("Do not use a comma.");
month = keyboard.nextInt( );
day = keyboard.nextInt( );
year = keyboard.nextInt( );
}
}
This is the DateTest class.
package datetest;
public class DateTest {
public static void main(String[] args) {
Date today = new Date();
System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 2. today = new Date(55, 55, 2011);
//Line 3. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 4. today.set(10, 5, 2011);
//Line 5. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
}
}
I have attempted to write the code to call the methods in step 4. Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Yes, if you used your m, d, and y arguments instead of month, day, and year:
public Date (int m, int d, int y) {
this.setMonth(m);
this.setDay(d);
this.setYear(y);
}
With your code, you're actually just setting the instance members (month and so on) to their existing values (because month in the constructor is automatically resolved to the instance data member month using an implied this.). So I'm guessing when you tried it, you ended up with zeroes and didn't understand why. (int members are auto-initialized to zero before the code in the constructor runs.)
Any idea why my code won't show the result? Maybe I messed up something, just new to programming by the way.
The goal of the program is to see if the date given by the main class is valid or not, it's not that specific on details such as the month of February and leap years so its pretty simple.
This is my DataRec.java :
public class DateRec {
int month, day, year;
boolean good;
public DateRec (){
month = 1;
day = 1;
year = 2008;
good = true;
}
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
}
public void validate (){
if ((month < 0) || (month > 12)){
good = false;
if (year == 0)
good = false;
if ((day < 0) || (day > 31))
good = false;
}
}
#Override
public String toString() {
if (good = true) {
return String.format("%dd/%dd/%dddd", month, day, year);
} else {
return String.format("%dd/%dd/%dddd", month, day, year);
}
}
}
This is my main class DataRecTest.java:
public class DateRecTest {
public static void main (String[] args){
DateRec today = new DateRec(1,2,2014);
DateRec anyDay = new DateRec();
DateRec noDay = new DateRec(13,31,2014);
anyDay.validate();
today.validate();
noDay.validate();
today.toString();
anyDay.toString();
noDay.toString();
}
}
Default value of boolean (good) is false so you need to initialized good in constructor or validate() function i.e
good = true; // in constructor or validate function
To see the results you need to print them.
//To print in java use System.out.print() or println();
System.out.println(today.toString());
//or simply
System.out.println(today); // println will call today.toString() internally
[EDIT]
Since you are storing result in good I recommend the following:
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
good = true;
validate();
}
Now you don't need to call validate() every-time; just check the value of good
your validate() is wrong.... It will always be set t false (default value) in whenever you use the 3- argument constructor. You are not setting it to true when date is correct.
change it to,
public void validate (){
if ((month <= 0) || (month > 12) || (year==0) || (day<=0) || (day>31)){
good = false;
}
else
{
good=true;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a project in school to solve year 2000 with java. here is the description of the assignment:
Create a Date object with the following:
attribute: a julian date representing the number of days since Jan 1, 1501 (the epoch date for this project) - this should be a private member variable of the class with the associated accessor and mutator methods.
constants: a suitable constant for each month
a suitable contant for each component of the epoch date
method: Date(long year, long month, long day) that converts the given year, month, and day to the julian date.
method: a method that converts a year, month, and day into the number of days since the project's epoch date.
method: a method that determines if a given year is a leap year
method: a method that returns the number of days in a given year; replace the current simple if statement with a single statement using the conditional operator (? :)
method: a method that returns the number of days in a given month of a given year; method should implement a switch statement using appropriate constants.
methods: any of the other methods developed in class should probably also be included.
method: returnYear() a method that determines the year component of the julian date value
method: returnMonth() a method that determines the month component of the julian date value
method: returnDay() a method that determines the day component of the julian date value
method: returnMonthName() a method that returns the name of the given month ( if month = JAN return "January" (use a switch statement))
method: returnDate() a method that returns the date in the format monthName day, year
class: Utility containing two query methods.
And here is the code I came with so far.. it is not compiling because there is something wrong with the switch!
import java.util.Scanner;
class Date
{
public final static long EPOCHYEAR = 1501;
private long julianDate;
Date(long year, long month, long day)
{
julianDate = returnTotalJulianDay(year, month, day);
System.out.println("Days is " + julianDate);
}
boolean isLeapYear(long year)
{
boolean answer;
if(year % 4 == 0 && (year % 4 == 0 || year % 100 != 0))
{
answer = true;
}
else
{
answer = false;
}
return answer;
}
long returnDaysInMonth(long year, long month)
{
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
return 31;
}
else if(month == 4 || month == 6 || month == 9 || month == 11)
{
return 30;
}
else if(isLeapYear(year))
{
return 29;
}
else
{
return 28;
}
}
long returnJulianDate(long year, long month, long day)
{
long julianDate;
long monthCounter;
julianDate = 0;
monthCounter = 1;
while(monthCounter < month)
{
julianDate += returnDaysInMonth(year, monthCounter);
monthCounter += 1;
}
julianDate += day;
return julianDate;
}
long returnTotalJulianDay(long year, long month, long day)
{
long totalJulianDay = 0;
long yearCounter = 1;
while(yearCounter < year)
{
totalJulianDay += returnJulianDate(year, month, yearCounter);
yearCounter += 1;
}
return totalJulianDay;
}
long returnDaysInYear(long year)
{
final long DAYSINYEAR = 365;
if(isLeapYear(year))
{
return 366;
}
else
{
return DAYSINYEAR;
}
}
long returnJulianEpochDays(long year, long month, long day)
{
long yearCounter = EPOCHYEAR;
long total = 0;
while(yearCounter < year)
{
total += returnDaysInYear(yearCounter);
yearCounter += 1;
}
total += returnJulianDate(year, month, day);
return total;
}
long returnYear()
{
long dayCounter = 0;
long yearCounter = EPOCHYEAR;
for(dayCounter = this.julianDate; dayCounter > returnDaysInYear(yearCounter); yearCounter++)
{
dayCounter -= returnDaysInYear(yearCounter);
}
return yearCounter;
}
long returnMonth()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return monthCounter;
}
long returnDay()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return julianEpochDays;
}
long returnMonthName()
{
int month = 0;
final int JAN = 1;
final int FEB = 2;
final int MAR = 3;
final int APR = 4;
final int MAY = 5;
final int JUN = 6;
final int JUL = 7;
final int AUG = 8;
final int SEP = 9;
final int OCT = 10;
final int NOV = 11;
final int DEC = 12;
switch(month)
{
case JAN:
return "January";
case FEB:
return "Febuary";
case MAR:
return "March";
case APR:
return "April";
case MAY:
return "May";
case JUN:
return "June";
case JUL:
return "July";
case AUG:
return "August";
case SEP:
return "September";
case OCT:
return "October";
case NOV:
return "November";
case DEC:
return "December";
}
}
}
class utility
{
public char queryForCharacter(String prompt)
{
int typedCharacter = ' ';
try
{
System.out.print(prompt);
typedCharacter = System.in.read();
}
catch(Exception e)
{
}
return (char) typedCharacter;
}
public static long queryForLong(String prompt)
{
Scanner keyboard;
long theNumber;
keyboard = new Scanner(System.in);
System.out.print(prompt);
theNumber = keyboard.nextInt();
return theNumber;
}
}
public class DateDriver
{
public static void main(String[] args)
{
Date aTestDate = null;
aTestDate = new Date(1502, 1, 1);
}
}
Your method returnMonthName() is declared to return a long, but the switch cases return Strings.
Also, the method needs to return something if none of the cases in the switch match.
Your function returns a type of long:
"long returnMonthName() {"
But your are returning a type of "String". i.e. "January".