Missing Format Argument Exception - java

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}

System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Related

Why does it display the value "null" if the conditions of the method are met?

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());
}
}

Java not outputting or requesting keyboard input

I am having trouble getting my java code to properly output the required results. Not to mention that my System.out.Println isn't prompting for input. All my code is good with no errors. However it just doesn't seem to output anything or request an input.
//Author Adam Duffy
package test1;
import java.util.Scanner;
public class Employee {
public static void main(String [ ] args){}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
{
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
}
I just can't seem to get it to work. I'm sure I'm missing something obvious. If I could get some advice, I would be very appreciative.
Updated peice of code , which will accept and print the number on console.
public class Employee {
public static void main(String [ ] args){
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
}
public String DEF_EMP_NUM = "NO_EMP_NUM";
public double DEF_RATE_PER_HOUR = 20.0;
public double DEF_OVER_TIME_RATE = 40.0;
public double DEF_RATE_HOURS_PER_WEEK = 1.5;
private String empNum;
private double ratePerHour;
private double baseHrsPerWeek;
private double overTimeRate;
// no arg constructor setting width and length to default of 1
public Employee() {
empNum = DEF_EMP_NUM;
ratePerHour = DEF_RATE_PER_HOUR;
baseHrsPerWeek = DEF_RATE_HOURS_PER_WEEK;
overTimeRate = DEF_OVER_TIME_RATE;
}
// all arg constructor
public Employee(String empNum, float ratePerHour, float baseHrsPerWeek, int overTimeRate) {
this.empNum = empNum;
this.ratePerHour = ratePerHour;
this.baseHrsPerWeek = baseHrsPerWeek;
this.overTimeRate = overTimeRate;
}
//setters
public void setempNum(String empNum) {
this.empNum = empNum;
}
public String getempNum() {
return this.empNum;
}
//methods
public double getratePerHour() {
return ratePerHour;
}
public void setratePerHour(float ratePerHour) {
this.ratePerHour = ratePerHour;
}
public double getoverTimeRate() {
return overTimeRate;
}
public int setoverTimeRate(int overTimeRate) {
this.overTimeRate = overTimeRate;
return overTimeRate;
}
public double getbaseHrsPerWeek() {
return baseHrsPerWeek;
}
public void setbaseHrsPerWeek(float baseHrsPerWeek) {
this.baseHrsPerWeek = baseHrsPerWeek;
}
#Override
public String toString() {
return super.toString()
+ "\n["
+ "\nbaseHrsPerWeek = " + baseHrsPerWeek
+ "\noverTimeRate = " + overTimeRate
+ "\nratePerHour = " + ratePerHour
+ "\nempNum = " + empNum
+ "\n]";
}
public double calcWeeksPay(int hours) {
return this.ratePerHour * this.baseHrsPerWeek;
/*#param hours
#return
*/
}
}
Problem was that you were not having anything in the psvm method and below piece of code
Scanner scan = new Scanner(System.in);
int myNum[] = new int[5];
int i;
int sum = 0;
for (i = 0; i < myNum.length; i++) {
System.out.print("Enter the number " + (i + 1) + " : ");
myNum[i] = scan.nextInt();
}
for (i = 0; i < myNum.length; i++) {
System.out.print("The number " + (i + 1) + " : ");
System.out.print(myNum[i] + "\n+");
for (int e = 1; e <= i; e++) {
sum = sum + e;
}
System.out.println(sum);
}
Which takes the input and print it on console was not having any calling code. it was just a inside the block of code. i just moved it inside the main method and it worked.

(Arraylist) Crashes when user defined String input

The purpose of the program is to let the user input 5 numbers and select which game they would like to compare them to (lotto/lottoplus1/lottoplus2) with each having a unique set of 5 numbers, then to be stored in an arraylist.
The national lottery run three draws on each night: Lotto, Lotto plus one and Lotto plus 2.
generate numbers for each of these draws.
When a user enters a line of numbers they should also enter either:"lotto", "plus1", or "plus2" to specify which of the draws their numbers should be compared to.
This value should then be assigned to that specific line of numbers and the numbers on that line should be compared against each set of Lotto numbers as required.
Heres my problem! When I input my five numbers then lets say 'plus1' to assign the comparison of those numbers to lotteryPlusOne it crashes and outputs this message:
Exception in thread "main" java.lang.NullPointerException at lottoapp.lottoCounter.compareNums(lottoCounter.java:136) at lottoapp.LottoApp.main(LottoApp.java:61) C:\Users\x15587907\AppData\Local\NetBeans\Cache\8.1\executor‌​-snippets\run.xml:53‌​: Java returned: 1 BUILD FAILED (total time: 15 seconds)
Below is line 136 it is in the Instantiable class in the public void compareNums() method
l = madeUpArrayList.get(i); <-----
Main App
package lottoapp;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.Arrays;
public class LottoApp {
public static void main(String[] args) {
//declare vars/objects/arrays
int[] lottery = new int[5]; //5 Winning numbers
int[] lotteryPlus1 = new int[5]; //5 Winning LP1 numbers
int[] lotteryPlus2 = new int[5]; //5 Winning LP2 numbers
String gameType;
int number1;
int number2;
int number3;
int number4;
int number5;
//array list called madeUpArrayList
ArrayList<lottoCounter> madeUpArrayList = new ArrayList();
//object declare and create
lottoCounter myCount = new lottoCounter();
//winNums/getLottery need to be initialised at top of program
myCount.winNums();
lottery = myCount.getLottery();
lotteryPlus1 = myCount.getLotteryPlus1();
lotteryPlus2 = myCount.getLotteryPlus2();
//Displays winning numbers (Testing Purposes)
System.out.println(Arrays.toString(lottery));
System.out.println(Arrays.toString(lotteryPlus1));
System.out.println(Arrays.toString(lotteryPlus2));
//Array List
for (int i = 0; i < 1; i++) {
lottoCounter l = new lottoCounter();
number1 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 1 "));
number2 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 2 "));
number3 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 3 "));
number4 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 4 "));
number5 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 5 "));
gameType = JOptionPane.showInputDialog(null, "Select a game type for comparison ... lotto/plus1/plus2");
l.setNumber1(number1);
l.setNumber2(number2);
l.setNumber3(number3);
l.setNumber4(number4);
l.setNumber5(number5);
l.setGameType(gameType);
madeUpArrayList.add(l);
}
//Comparison
myCount.compareNums();
//Output Lotto,Lotto Plus One and Lotto plus Two correct guesses
JOptionPane.showMessageDialog(null, "Guesses correct for Regular Lottery correct is " + myCount.getCorrectLotto());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus One is " + myCount.getCorrectPlusOne());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus Two is " + myCount.getCorrectPlusTwo());
}
}
Instantiable Class
package lottoapp;
import java.util.ArrayList;
public class lottoCounter {
//Variables/Constants/data members
private int correctLotto;
private int correctPlusOne;
private int correctPlusTwo;
private int[] lottery = new int[5];
private int[] lotteryPlus1 = new int[5];
private int[] lotteryPlus2 = new int[5];
private int number1;
private int number2;
private int number3;
private int number4;
private int number5;
private String gameType;
private ArrayList<lottoCounter> madeUpArrayList;
//Constructor
lottoCounter() {
correctLotto = 0;
correctPlusOne = 0;
correctPlusTwo = 0;
number1 = 0;
number2 = 0;
number3 = 0;
number4 = 0;
number5 = 0;
gameType = " ";
}
//setters
public void setCorrectLotto(int correctLotto) {
this.correctLotto = correctLotto;
}
public void setCorrectPlusOne(int correctPlusOne) {
this.correctPlusOne = correctPlusOne;
}
public void setCorrectPlusTwo(int correctPlusTwo) {
this.correctPlusTwo = correctPlusTwo;
}
public void setLottery(int[] lottery) {
this.lottery = lottery;
}
public void setLotteryPlus1(int[] lotteryPlus1) {
this.lotteryPlus1 = lotteryPlus1;
}
public void setLotteryPlus2(int[] lotteryPlus2) {
this.lotteryPlus1 = lotteryPlus2;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setNumber3(int number3) {
this.number3 = number3;
}
public void setNumber4(int number4) {
this.number4 = number4;
}
public void setNumber5(int number5) {
this.number5 = number5;
}
public void setGameType(String gameType) {
this.gameType = gameType;
}
public lottoCounter(ArrayList<lottoCounter> madeUpArrayList) {
this.madeUpArrayList = madeUpArrayList;
}
//COMPUTE
//Lottery Generator | random num generator (1-40)Lottery
public void winNums() {
for (int i = 0; i < lottery.length; i++) {//Generating 1 to 40 numbers
lottery[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lottery[i] == lottery[j]) {
i--;
}
}
}
//Lottery plus 1 generator
for (int i = 0; i < lotteryPlus1.length; i++) {//Generating 1 to 40 numbers
lotteryPlus1[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus1[i] == lotteryPlus1[j]) {
i--;
}
}
}
//Lottery plus 2 generator
for (int i = 0; i < lotteryPlus2.length; i++) {//Generating 1 to 40 numbers
lotteryPlus2[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus2[i] == lotteryPlus2[j]) {
i--;
}
}
}
}
//Counter for Lottery/LotteryPlusOne/LotteryPlusTwo (COMPARISON)
public void compareNums() {
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
lottoCounter l;
l = madeUpArrayList.get(i);
if (l.getGameType().equals("lotto")) {
if (lottery[j] == l.getNumber1() || lottery[j] == l.getNumber2() || lottery[j] == l.getNumber3() || lottery[j] == l.getNumber4() || lottery[j] == l.getNumber5()) {
correctLotto++;
}
}
if (l.getGameType().equals("plus1")) {
if (lotteryPlus1[j] == l.getNumber1() || lotteryPlus1[j] == l.getNumber2() || lotteryPlus1[j] == l.getNumber3() || lotteryPlus1[j] == l.getNumber4() || lotteryPlus1[j] == l.getNumber5()) {
correctPlusOne++;
}
}
if (l.getGameType().equals("plus2")) {
if (lotteryPlus2[j] == l.getNumber1() || lotteryPlus2[j] == l.getNumber2() || lotteryPlus2[j] == l.getNumber3() || lotteryPlus2[j] == l.getNumber4() || lotteryPlus2[j] == l.getNumber5()) {
correctPlusTwo++;
}
}
}
}
}
//getters (return values to App Class)
public int getCorrectLotto() {
return correctLotto;
}
public int getCorrectPlusOne() {
return correctPlusOne;
}
public int getCorrectPlusTwo() {
return correctPlusTwo;
}
public int[] getLottery() {
return lottery;
}
public int[] getLotteryPlus1() {
return lotteryPlus1;
}
public int[] getLotteryPlus2() {
return lotteryPlus2;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
public int getNumber4() {
return number4;
}
public int getNumber5() {
return number5;
}
public String getGameType() {
return gameType;
}
public ArrayList<lottoCounter> getMadeUpArrayList() {
return madeUpArrayList;
}
}
I am not sure about anyone else but it would be nice to have more info, like the data in the arrays: lottery, lotteryPlus1 and madeUpArrayList ect. Just to make sure that they actually have any data in them because according to your Exception you have a java.lang.NullPointerException in your method compareNums in line 136 of your class. Because you did not post line numbers I am not sure when the exception occurs.
I am assuming one of your arrays does not have any data in it or one or more of your arrays do not have 5 total entries of data in it because your for loop iterates 5 times. But again without seeing how or when your arrays are instantiated I do not think it is possible for anyone to confirm that is the cause of your problems. For example lotteryPlus2[] may only have data for lotteryPlus2[0],lotteryPlus2[1],and lotteryPlus2[2] so when j gets to 3 in the loop lotteryPlus2[3] does not exist and throws a java.lang.NullPointerException.
Also I am curious on why you use this for loop for (int i = 0; i < 1; i++){}
This loop only loops once no matter what so why have it there at all since your main method will always run at least once anyways? Honest question, I am a beginner programmer so you may be using it for something that I have no knowledge about.

How do I input&solve expressions like sin(60)*50/4 in my simple calculator(without GUI) in Java?

I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}

Method Not Displaying Properly

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>();

Categories