Adding Time Program Compiler Error: cannot find symbol [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
My programming class was instructed to make a program that would add time and converting it into the right minutes and seconds amount (no bigger than 59.)
import java.util.Scanner;
public class AddingTime {
public static void main (String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Welcome to AddingTime!");
// First Addend
System.out.println("Enter the days amount for the first addend (if none print 0): ");
int firstAddendDays = kbReader.nextInt();
System.out.println("Enter the hours amount for the first addend (in none print 0): ");
int firstAddendHours = kbReader.nextInt();
System.out.println("Enter the minutes amount for the first addend (if none print 0): ");
int firstAddendMinutes = kbReader.nextInt();
System.out.println("Enter the seconds amount for the first addend (if none print 0): ");
int firstAddendSeconds = kbReader.nextInt();
// Second Addend
System.out.println("Enter the days amount for the second addend (if none print 0): ");
int secondAddendDays = kbReader.nextInt();
System.out.println("Enter the hours amount for the second addend (in none print 0): ");
int secondAddendHours = kbReader.nextInt();
System.out.println("Enter the minutes amount for the second addend (if none print 0): ");
int secondAddendMinutes = kbReader.nextInt();
System.out.println("Enter the seconds amount for the second addend (if none print 0): ");
int secondAddendSeconds = kbReader.nextInt();
int totalSeconds = firstAddendSeconds + secondAddendSeconds;
if (totalSeconds >= 60) {
// Total Seconds if totalSeconds is larger than 60
totalSeconds = totalSeconds % 60;
// Extra minutes from totalSeconds in a decimal form
double minutesFromSeconds = totalSeconds / 60;
// Changing the above into a integer form of minutes
int intMinutesFromSeconds = (int)minutesFromSeconds;
}
int totalMinutes = firstAddendMinutes + secondAddendMinutes + intMinutesFromSeconds;
if (totalMinutes >= 60) {
// Total minutes if totalMinutes is larger than 60
totalMinutes = totalMinutes % 60;
// Extra hours from totalMinutes in a decimal form
double hoursFromMinutes = totalMinutes / 60;
// Changing the above into an integer form of hours
int intHoursFromMinutes = (int)hoursFromMinutes;
}
int totalHours = firstAddendHours + secondAddendHours + intHoursFromMinutes;
if (totalHours >= 24) {
// Total hours if totalHours is larger than 24
totalHours = totalHours % 24;
// Extra days from totalHours in a decimal form
double daysFromHours = totalMinutes / 24;
// Changing the above into an integer form of days
int intDaysFromHours = (int)daysFromHours;
}
int totalDays = firstAddendDays + secondAddendDays + intDaysFromHours;
System.out.println("Your total calculated time is " + totalDays + "days" + totalHours + "hours" + totalMinutes + "minutes" + totalSeconds + "seconds" );
}
}
When I compile this code, it tells me that I have an cannot find symbol error on variable intMinutesFromSeconds, intHoursFromSeconds, and intDaysFromHours. Why?

It may be a problem with scope (what's declared inside the brackets may not be available after the brackets close). Not sure what Java is doing.
if (totalSeconds >= 60) {
int intMinutesFromSeconds = (int) minutesFromSeconds;
}
int totalMinutes = intMinutesFromSeconds + ...
You can fix it with something like:
int intMinutesFromSeconds = 0;
if (totalSeconds >= 60) {
intMinutesFromSeconds = (int) minutesFromSeconds;
}
int totalMinutes = intMinutesFromSeconds + ...

Related

Change the value of a global variable inside a for loop

I am creating a small program, for a school assignment, in which people can input their running history (miles run, time elapsed) and see their potential 10K pace and marathon pace times. After the paces are displayed, a table of different paces is displayed.
I have a global variable (pace) which most of the calculations run with that needs to be altered inside a for loop but will not update for the calculations.
edit: I understand this program is poorly written and there's a lot of stuff that could be condensed. However, it works and will satisfy the parameters of the assignment. Inside the for loop, the variable "pace" needs to be increased by 30 with every iteration of the loop.
public class MarathonTime {
public static void main(String[] args) {
String name;
double distance;
int hours, minutes, seconds;
double pace;
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.print("What is your first name? ");
name = scanner.next();
System.out.print("How many miles did you run today? ");
distance = scanner.nextDouble();
System.out.print("How long did it take? Hours: ");
hours = scanner.nextInt();
System.out.print("Minutes: ");
minutes = scanner.nextInt();
System.out.print("Seconds: ");
seconds = scanner.nextInt();
pace = ((hours * 3600) + (minutes * 60) + seconds) / distance;
double marathonPace = pace * 26.2;
double tenKPace = pace * 6.2;
int paceMinutes, paceSeconds;
paceMinutes = (int) pace / 60;
paceSeconds = (int) pace % 60;
int marathonHours, marathonMinutes, marathonSeconds;
marathonHours = (int) marathonPace / 3600;
marathonMinutes = (int) (marathonPace % 3600) / 60;
marathonSeconds = (int) marathonPace % 60;
int tenKMinutes, tenKSeconds;
tenKMinutes = (int) tenKPace / 60;
tenKSeconds = (int) tenKPace % 60;
System.out.println("Hello " + name);
System.out.print("Your pace is "); timeFormatPace(paceMinutes, paceSeconds);
System.out.println();
System.out.print("At this rate your marathon time would be "); timeFormatMarathon(marathonHours, marathonMinutes, marathonSeconds);
System.out.println();
System.out.print("and your 10K time would be "); timeFormat10K(tenKMinutes, tenKSeconds);
System.out.println();
System.out.println("Good luck with your training!");
System.out.println();
for(int i = 1; i <= 10; i++){
if(i == 1) {
System.out.println("Pace \t\t 10K Time \t\t Marathon Time");
i++;
}
if(i == 2) {
System.out.println("------------------------------------------------------");
i++;
}
// input the tablePaces into the calcs and print them as the format
pace = (281 + (i*30));
if (i >= 3 && i <= 10) {
timeFormatPace(paceMinutes, paceSeconds); System.out.print("\t\t "); timeFormat10K(tenKMinutes, tenKSeconds); System.out.print("\t\t\t ");
timeFormatMarathon(marathonHours, marathonMinutes, marathonSeconds);
System.out.println();
}
}
}
I think this is what you're trying to do (very condensed):
public static void main(String[] args) {
int pace = 100; // or initialise to whatever
for(int i = 0; i < 10; i++) {
// do something
pace = pace + 30; // or equivalently, pace += 30
}
}
In future, try to reduce your problem to a minimal, complete and verifiable example. The process of doing this will often help you solve the problem yourself, but at the very least it makes it easy to for someone else.
Also, if you know your program is poorly written, fix it! Well written, concise, modular programs are much easier to reason about. Messy, complex code is difficult. You will thank yourself in less time spent debugging, and you'll get a better grade too.

How to determine the fewest number of each different coin needed to represent that entered amount?

I am very new to programing, and I am having trouble with this program which wants the user to enter a number of "alien coins" called novas and then determines the fewest number of each different alien coin needed to represent that amount, starting with the highest. Here are the coins and what they are worth:
1 aurora = 60 pulsars
1 pulsar = 70 gravitons
1 graviton = 6 novas
Here is a sample input and output on how it should look:
Enter number of novas: 64197 [Enter]
That number of novas is equal to:
2 auroras
32 pulsars
59 gravitons
3 novas
This is my code:
import java.util.Scanner;
public class AlienMoney {
public static void main(String[] args){
int startAmount, amount, auroras, pulsars, gravitons, novas;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of novas: ");
amount = input.nextInt();
System.out.println("That number of novas is equal to: ");
startAmount = amount;
gravitons = amount / 6;
amount = amount % 6;
pulsars = amount / 70;
amount = amount % 70;
auroras = amount / 60;
amount = amount % 60;
novas = amount;
System.out.println(auroras + " auroras");
System.out.println(pulsars + " pulsars");
System.out.println(gravitons + " gravitons");
System.out.println(novas + " novas");
}
}
And this is my output:
Enter number of novas: 64197 [Enter]
That number of novas is equal to:
0 auroras
0 pulsars
10699 gravitons
3 novas
I am not sure what I am doing wrong. I know I definitely have to use the modulus operator % to get the remainder, but I am not sure what to do after that. I would greatly appreciate anyone's help. Thank you.
You need to calculate your currencies in the correct order, starting from the largest.
So:
aurora > pulsar > graviton > nova
Instead of:
graviton > pulsar > aurora > nova
The approach in the code snippet below is to compute the number of novas in each of the three coins, and then to calculate how many of each coin to use to represent the amount entered.
In order to use the fewest number of coins, we should begin by using as many auroras as possible, with the remainder as pulsars, followed by gravitons last.
int auroras = amount / (6 * 70 * 60);
int remainder = amount % (6 * 70 * 60);
int pulsars = remainder / (6 * 70);
remainder = remainder % (6 * 70);
int graviton = remainder / 6;
int novas = remainder % 6;
Right here, problem lines indicated in comments:
startAmount = amount;
gravitons = amount / 6;
amount = amount % 6;
pulsars = amount / 70; // <-- starts here
amount = amount % 70;
auroras = amount / 60;
amount = amount % 60;
novas = amount;
You're using the wrong variables. Use the variables you assigned the needed amount into instead, e.g.:
startAmount = amount;
gravitons = amount / 6;
amount %= 6;
pulsars = gravitons / 70;
gravitons %= 70;
auroras = pulsars / 60;
pulsars %= 60;
novas = amount; // this doesn't need to change but there's no need to assign amount into a new variable
Also use the %= operator. It's pretty cool. ;)

How to turn minutes into years and days?

In the textbook it explains how to convert seconds into minutes with how many seconds remain but the question I have is as follows.
Write a program that prompts the user to enter the minutes (e.g., 1
billion), and displays the number of years and days for the minutes.
For simplicity, assume a year has 365 days. Here is an example.
Enter the number of minutes: 100000000
100000000 minutes is approximately 1902 years and 214 days.
What I currently have is as follows:
import java.util.Scanner;
public class Ch2_Exercise2_7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt user for number of minutes
System.out.println("Enter the number of minutes:");
int minutes = input.nextInt();
// Number of minutes in a year
int year = minutes / 525600;
int day = minutes / 1440;
int remainingMinutes = day % 525600;
System.out.println(minutes + " minutes is " + year + " years and " + remainingMinutes + " days ");
}
}
With what I have it isn't giving me the remaining minutes into days. For example, if I put in 525600 minutes it gives me 1 year and 365 days when it should just be 1 year.
I'm using Java Eclipse. Any help would be greatly appreciated! My apologies in advance if I post the code incorrectly.
You screwed up a bit over here:
// Number of minutes in a year
int year = minutes / 525600;
int day = minutes / 1440;
int remainingMinutes = day % 525600;
You took the total number of minutes and divided by 1440, so the number of days you got was wrong. You should have taken the remainder and then divided by 1440.
Another thing was in your print statement. You wrote the number of minutes left after one year as the number of days.
This should work:
// Number of minutes in a year
int year = minutes / 525600;
int remainingMinutes = minutes % 525600;
int day = remainingMinutes / 1440;
System.out.println(minutes + " minutes is approximately " + year + " years and " + day + " days.");
My main method is separate:
public class MinutesToYearsDaysCalculator {
public static void printYearsAndDays(long minutes) {
double days = minutes / 60 / 24;
double years = days / 365;
double remainingDays = days % 365;
System.out.println((minutes < 0 ? "Invalid Value" : minutes + " min = " + (int) years + " y and " + (int) remainingDays + " d"));
}
}
int mins,hours,remainingDays,days,years;
cout << "Enter minutes:";
cin >> mins;
hours = mins/60;
days = hours/24;
years = days/365;
remainingDays = days % 365;
cout << years << " years " << remainingDays << " days " << endl;
return 0;
public class MinutesToYearsDaysCalculator {
public static void printYearsAndDays(long minutes)
{
if(minutes<0) System.out.println("Invalid Value");
else
{
long hours = minutes/60;
long day = hours/24;
long years = day/365;
long remainingDays = day % 365;
System.out.println(minutes +" min = "+ years+" y and "+remainingDays +" d");
}
}
import java.util.Scanner;
public class Prog13 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter The Minute");
int min=sc.nextInt();
int year= min/(365*24*60);
int remaining_min=(min%24*60*60);
int day=remaining_min/24*60;
System.out.println( min + " " + " Minutes is approximately:"+ year + " " +"year"+ ' '+ day + "Day" );
}
}
hello you can use this result
import java.util.Scanner;
public class MinToYearsAndDays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("number of minutes:");
int minutes = input.nextInt();
int year = minutes / 525600;
int remainingMinutes = minutes % 525600;
int day = (remainingMinutes / 1440);
System.out.println(minutes + " minutes is approximately " + year + " years and " + day + " days ");
}
}
public class Mints_to_days_years {
// Given some numbers of minutes calculate the number of days and years
// from the given minutes.
// 1hr = 60 minutes
// 1 day = 24 hours
// 1 year = 365 days
public static void find_days_years(long minutes) {
if(minutes < 0) {
System.out.println("Invalid number of minutes.");
}
// to find the number of years, divide the nminutes by total numbers of minutes in a year.
long years = minutes / (60 * 24 * 365);
// then find the remainder minutes that does not goes exactly into year
long years_remainder = minutes % (60 * 24 * 365);
// divide the remainder by number of minutes in a day to find the numbers of days
long days = years_remainder / (60 * 24);
System.out.println(minutes + " mints = " + years + " yrs and " + days + " days.");
}
public static void main(String[] args) {
find_days_years(525600);
find_days_years(1051200);
find_days_years(561600);
}
}

Java: convert seconds to minutes, hours and days [duplicate]

This question already has answers here:
Convert seconds value to hours minutes seconds?
(22 answers)
Closed 6 years ago.
The task is:
The output should look like this (it is a good idea to echo back the input): You entered 500,000 seconds, which is 5 days, 18 hours, 53 minutes and 20 seconds. (5 days 18:53:20 hours)
How should I do it? What is the easiest way to understand and do it?
Also the instructor said "no hard coding" which I'm not exactly sure what is, but I think he wants us to assign them constants.
An example using the built-in TimeUnit.
long uptime = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);
With basic Java arithmetic calculations:
First consider the following values:
1 minute = 60 seconds
1 hour = 3600 seconds (60 * 60)
1 day = 86400 second (24 * 3600)
First divide the input by 86400. If you you can get a number greater than 0, this is the number of days.
Again divide the remained number you get from the first calculation by 3600. This will give you the number of hours.
Then divide the remainder of your second calculation by 60 which is the number of minutes
Finally the remained number from your third calculation is the number of seconds
The code snippet is as follows:
int input = 500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400) / 3600 ;
numberOfMinutes = ((input % 86400) % 3600) / 60
numberOfSeconds = ((input % 86400) % 3600) % 60;
It should be like:
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
(TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) -
(TimeUnit.SECONDS.toMinutes(seconds) *60);
System.out.println(
"Day " + day + " Hour " + hours + " Minute " + minute +
" Seconds " + second);
}
Explanation:
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e., day24*. You now got remaining hours.
The same for minute and second. You need to subtract the already got hour and minutes, respectively.
The simplest way:
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds ");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60) % 60;
int hours = (s / 60) / 60;
System.out.println(hours + ":" + min + ":" + sec);
Have a look at the class:
org.joda.time.DateTime
This allows you to do things like:
old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));
However, your solution probably can be simpler:
You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder.
You then need to work out how many hours in the remainder, followed by the minutes,
and the final remainder is the seconds.
This is the analysis done for you, and now you can focus on the code.
You need to ask what s/he means by "no hard coding". Generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in Java.
You should try this
import java.util.Scanner;
public class Time_converter {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int seconds;
int minutes;
int hours;
System.out.print("Enter the number of seconds: ");
seconds = input.nextInt();
hours = seconds / 3600;
minutes = (seconds % 3600) / 60;
int seconds_output = (seconds % 3600) % 60;
System.out.println("The time entered in hours,minutes and seconds is:");
System.out.println(hours + " hours: " + minutes + " minutes: " + seconds_output + " seconds");
}
}
You can use the Java enum TimeUnit to perform your math and avoid any hard-coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds: ");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
: "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
: "hours"));
sb.append(String.format("%d %s and ", minutesCount,
(minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
(secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
new DecimalFormat("#,###").format(secondsIn), sb, sb2);
Which, when I enter 500000, outputs the requested (manual line break added for post) -
You entered 500,000 seconds, which is 5 days, 18 hours,
53 minutes and 20 seconds. (5 days, 18:53:20 hours)
I started doing some pseudocode and came up with this:
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
// Variable declaration
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;
// Input
System.out.println("Enter amount of seconds!");
input = scan.nextInt();
// Calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;
// Output
if (input >= DYS) {
System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}
else if (input >= HRS && input < DYS) {
System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}
else if (input >= MIN && input < HRS) {
System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}
else if (input < MIN) {
System.out.println(input + " seconds equals to seconds");
}
scan.close();
}

Calculate number of years and days in mintues

Here is my code:
public class numberOfYears {
public static void main(String args[]){
String minsString = JOptionPane.showInputDialog("Enter numbers of minutes:");
double mins = Double.parseDouble(minsString);
//calcuate mins in a year
double minsOfaYear = 365*24*60;
double total = mins / minsOfaYear;
double year = total / 10;
double day = total / 10;
System.out.println(year+ " years and " + day + " days");
//result isnt right
}
}
The question is basically asking to enter minutes and the program supposedly to calculate it to years and days.. for instance, if I enter 1000000000 minutes it should give a result of 1902 years and 214 days.. but I am not getting the correct result. Can someone point out the problem for me please? Thank you!
You should convert the remainders of time to the smaller units of time. In example remainder of years should be converted to days, and remainder of days should be converted to hours etc.
Could you please try this:
public class numberOfYears {
public static void main(String args[]){
String minsString = JOptionPane.showInputDialog("Enter numbers of minutes:");
int mins = Int.parseInt(minsString, 16);
String time = ConvertTime(mins);
System.out.println(time);
}
}
// Convert minutes to years, days, hours an minutes
public String ConvertTime(int time){
String result = "";
int years = time/(365*24*60);
int days = (time%(365*24*60))/(24*60);
int hours= (time%(365*24*60)) / 60;
int minutes = (time%(365*24*60)) % 60;
result = years+" years " + days + " days "+ hours + " hours " + minutes + " minutes";
return result;
}
public class numberOfYears {
public static void main(String args[]){
String minsString = JOptionPane.showInputDialog("Enter numbers of minutes:");
double mins = Double.parseDouble(minsString);
//calcuate mins in a year
double minsOfaYear = 365*24*60;
double year = mins / minsOfaYear;
double day = (mins % minsOfaYear)/(24*60);
System.out.println((int)year+ " years and " + (int)day + " days");
}
}
For this kind of math problem, we need to make use of integer division. If the number of minutes works out to be 45.8 years, you want this to be calculated as 45 years and then convert the remainder of 0.8 years into days. Its not clear to me why your code has a / 10
Try this:
public class numberOfYears {
static double minsOfaYear = 365*24*60;
public static void main(String args[]) {
String minsString = JOptionPane.showInputDialog("Enter numbers of minutes:");
double mins = Double.parseDouble(minsString);
//calcuate mins in a year
int year = (int) (mins / minsOfaYear);
double day = mins - year*minsOfaYear;
System.out.println(year+ " years and " + day + " days");
}
}
I would do it this way
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.MINUTE, 1000000000);
int year1 = c1.get(Calendar.YEAR);
int day1 = c1.get(Calendar.DAY_OF_YEAR);
int year2 = c2.get(Calendar.YEAR);
int day2 = c2.get(Calendar.DAY_OF_YEAR);
int years;
int days;
if (day2 > day1) {
years = year2 - year1;
days = day2 - day1;
} else {
c2.add(Calendar.YEAR, -1);
years = year2 - year1 - 1;
days = c2.getActualMaximum(Calendar.DAY_OF_YEAR) - day1 + day2;
}
System.out.println(years + " years " + days + " days from now");
output
1901 years 119 days from now

Categories