I am writing a program for class and the loop seems to not execute correctly. It always returns the value for i as 0. The rest of the code seems to work as advertised, i is just not increasing in index value.
public class Day {
String strDay;
private int d = 0;
private String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String day;
public Day() {
return;
}
public Day(String strDay) {// this is my issue. I think I am going about this constructor all wrong
for (int i = 0; i < Days.length; i++) {
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
public int getDay() {
return d;
}
public void nexDay() {
int next;
if (d < 6) {
next = (this.d) + 1;
System.out.println("Next Day is :" + Days[next]);
} else {
next = 0;
System.out.println("Next Day is :" + Days[next]);
}
}
public void prevDay() {
int prev = 0;
if ((d > 0) && (d < 6)) {
prev = (this.d) - 1;
System.out.println("previous day is " + Days[prev]);
} else
System.out.println("previous day id " + Days[6]);
}
public int calcDay(int num) {
int newDay;
this.d = d + num;
newDay = this.d % 7;
System.out.println("calc day is" + Days[d]);
return newDay;
}
public void print() {
System.out.println("day is " + Days[d]);
}
public static void main(String[] args) {
String day;
Day Callmethod = new Day();
Scanner console = new Scanner(System.in);
System.out.println("enter a day of the week");
day = console.nextLine();
Callmethod.print();
Callmethod.nexDay();
Callmethod.prevDay();
Callmethod.getDay();
}
}
Well, this
Day Callmethod = new Day();
is calling your empty constructor. Not your constructor with a loop (which takes a String). Also, Java variables start with a lower case letter (Callmethod looks like a class). I think you were looking for something like
Day day = new Day("SUNDAY");
Also, your if needs braces or the return will be invoked without doing anything (unless it matches on the first entry) like
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i])) {
d = i;
return;
}
}
try change this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
for this:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
{
d = i;
return;
}
}
}
Without the curly braces your conditional block will be only the next line of code. So your loop was only running once
public Day(String strDay) {
for (int i = 0; i < Days.length; i++) {
if (strDay == Days[i])
d = i;
return;
}
}
If I understood it clearly this will work. If not, just explain me what the goal is on that for loop. And place the return statement outisde of the next bracket.
Related
I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}
I am currently working on my homework which is simulation to an alarm, I have a method called removeAlarm() , I wanna force remove the alarm which I added, I tried alarm.remove(0) and tried to iterator but in the test program the alarm is still there.
Does anyone observe the issue?
private ArrayList<String> alarm;
public AlarmClock() throws IllegalValueException {
super();
alarm = new ArrayList<String>();
}
public AlarmClock(int hour, int minute) throws IllegalValueException {
super(hour, minute);
alarm = new ArrayList<String>();
}
public void addAlarm(int hour, int minute) throws IllegalValueException {
int limit = 2;
int length = String.valueOf(hour).length();
String displayValue = "";
for (int i = 0; i < limit - length; i++) {
displayValue = displayValue + "0";
}
displayValue = displayValue + hour + ":";
limit = 2;
length = String.valueOf(minute).length();
for (int i = 0; i < limit - length; i++) {
displayValue = displayValue + "0";
}
displayValue = displayValue + minute;
alarm.add(displayValue);
}
public void removeAlarm() {
if (alarm.equals(getClass())) {
alarm.remove(alarm.equals(getTime()));
}
}
super.timeTick();
for (int x = 0; x < alarm.size(); x++) {
if (alarm.get(x).equals(getTime())) {
System.out.println("LARMET ÄR KLARR, VAKNAAAAA");
alarm.remove(x);
} else {
return;
}
}
My test program
try {
AlarmClock alarm = new AlarmClock(12, 3);
alarm.timeTick();
System.out.println(alarm.getTime());
alarm.timeTick();
System.out.println(alarm.getTime());
alarm.removeAlarm();
alarm.addAlarm(12, 6);
alarm.timeTick();
System.out.println(alarm.getTime());
} catch (IllegalValueException a) {
System.out.println(a.getMessage());
}
System.out.println("Expected: alarm removed at 12:06 ");
System.out.println(" ");
Output
12:04
12:05
LARMET ÄR KLARR, VAKNAAAAA
12:06
Expected: alarm removed at 12:06
alarm.remove(0) will remove the first item in the list. To remove an item from anywhere in the list the function would have to be
void removeAlarm(int target) {
alarm.remove(target);
}
or
void removeAlarm(int hour, int min) {
alarm.remove{hour+":"+min);
}
for just removing the last alarm:
void removeLastAlarm() {
alarm.remove(alarm.size()-1);
}
Having some problems with this program. I am new to Java and am trying to make a league scheduler. I have got to the point where the user can enter a number of teams needed, expected league start date and end date. Once the user selects the end date, a number of rounds are suggested to the user as this would be the number of weeks the league would need to go on for. Currently though, when the league generates, the dates print altogether, my question is how can I can the dates to print like - "round 1 05/06/2018". Also, how can I change my program so an odd number can be accepted, similar to a 'bye'?
I apologise for my ill knowledge of the subject, I have included a snippet of my code and a picture of my GUI so it gives more context.
Many thanks,
Jack
void cyclicRoll(int cycle[], int teams) {
int tmp = cycle[1];
for(int i=1;i<teams-1;i++) {
int pr = cycle[i+1];
cycle[i+1] = tmp;
tmp = pr;
}
cycle[1] = tmp;
}
void scheduleTournament(int teams, int round) {
if (((teams%2 != 0) && (round != teams - 1))||(teams <= 0))
throw new IllegalArgumentException();
int[] cycle = new int[teams];
int n = teams /2;
for (int i = 0; i < n; i++) {
cycle[i] = i + 1;
cycle[teams - i - 1] = cycle[i] + n;
}
Date startDate = (jXDatePicker1.getDate());
Date endDate = (jXDatePicker2.getDate());
LocalDate dates = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstdate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
DayOfWeek dayOfWeeek = dates.getDayOfWeek();
LocalDate datee = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
String listrep ="";
String firstDateToPrint = firstdate.toString();
while (!dates.equals(datee)) {
jTextArea1.removeAll();
if(dayOfWeeek == dayOfWeeek) {
dates = dates.plusDays(7);
}
String[] Itdates = {dates.toString()
};
for(String replacement : Itdates) {
if ("".equals(listrep)) {
listrep += replacement;
} else {
listrep += ", \n" + replacement ;
}
}
}
jTextArea1.append(firstDateToPrint + "\n");
jTextArea1.append(listrep);
for(int d = 1; d <= round; d++)
{
jTextArea1.append(String.format("Round %d\n", d ));
for (int i = 0; i < n; i++)
{
jTextArea1.append(String.format("team %d - team %d\n",cycle[i],cycle[teams - i - 1]));
}
//Roll the cycle keeping the first constant
cyclicRoll(cycle,teams);
}
}
String ref;
String teams;
String rounds;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.selectAll();
jTextArea1.replaceSelection("");
teams = jTextField1.getText();
int teamsToEnter = Integer.parseInt(teams);
rounds = jTextField2.getText();
int roundsToEnter = Integer.parseInt(rounds);
ref = jTextField3.getText();
jTextArea1.append("Ref "+ref + "\n");
scheduleTournament(jTextField2,roundsToEnter);
}
I am working on a program that takes user input for an array. One method I have FindLowestTempInArray returns the lowestDay (the position in the array). I want to print the index and the value at that spot in my main method. I have been searching and I dont know a simple way to do this. Right now I have been just been printing the data from the methods without returning the values. That works but I want to know how to print the values from the main. So once again all I am wondering is how to print both the lowestTemp and the lowestDay from the method in the main.
Here is my code I have:
public static int FindLowestTempInArray(int[] T)
{
// Returns the index of the lowest temperature in array T
int lowestTemp = Uninitialized;
int lowestDay = 0;
for(int day = 0; day < T.length; day++)
{
if(T[day] != Uninitialized && ( T[day] < lowestTemp || lowestTemp == Uninitialized))
{
lowestTemp = T[day];
lowestDay = day;
return lowestTemp;
}
}
return lowestDay;
}
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] high = new int[32];
int [] low = new int[32];
Init (high);
Init(low);
LoadData(high,low);
Report(high, low);
FindAvg(high);
//FindAvg(low);
//why do i not need to do both the one above and FindAvg(low);
System.out.println("The average for the high is: " + FindAvg(high));
System.out.println("The average for the low is: " + FindAvg(low));
//Lowest(high, low);
FindLowestTempInArray(high);
System.out.println(FindLowestTempInArray(high) + "\n" + FindLowestTempInArray(low));
Highest(high,low);
System.out.println("\n" + "The highest high is: " + Highest(high, low) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(high, low));
System.out.println("\n" + "The highest low is: " + Highest(low, high) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(low, high));
// LeastToGreatest(high, low);
}
There are 2 ways:
Change the return type of your FindLowestTempInArray to int[] i.e integer array and say int[0] islowest temperature and int[1] is lowest day
you can create a new class say Temperature with 2 class variables say temperature and day, and in your method FindLowestTempInArray you can have return type of Temperature and you can set the Temperature object in that method.
Below is sample of return type int[].
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
int[] lowest = new int[2];
lowest = FindLowestTempInArray(low);
System.out.println(lowest[0] + " " + lowest[1]);
}
public static int[] FindLowestTempInArray(int[] T) {
int[] lowest = new int[2];
lowest[0] = Uninitialized;
lowest[1] = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < lowest[0] || lowest[0] == Uninitialized)) {
lowest[0] = T[day];
lowest[1] = day;
}
}
return lowest;
}
}
Solution 2(Inner Class):
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
Weather.Temperature temp = FindLowestTempInArray(low);
System.out.println(temp.temperature + " " + temp.day);
}
public static Weather.Temperature FindLowestTempInArray(int[] T) {
Weather.Temperature temp=new Weather.Temperature();
temp.temperature = Uninitialized;
temp.day = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < temp.temperature || temp.temperature == Uninitialized)) {
temp.temperature = T[day];
temp.day = day;
}
}
return temp;
}
static class Temperature{
private int temperature;
private int day;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
}
One way would be to change the return type of public static int FindLowestTempInArray(int[] T) to int[], so that you can return both values. Otherwise, as soon as one return statement is executed, the method is exited.
You can use lowest[0] for the day and lowest[1] for the temp, or vice versa.
Another way is to get these two values separately (using parameters to distinguish which return value you want) and store them in two variables. The idea is to get these values stored somewhere in the main method to be able to play with them.
After you do that, you can use System.out to display the values, as desired.
The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();