arraylist in java, getting all the data print out - java

I am learning Java right now and I am trying to use ArrayList in my project, but it doesn't work. Help please...
public class TestCalculator {
public static void main(String[]args){
ArrayList<BMICalculator> bmilist = new ArrayList<>();
//ArrayList<Double> bmilist = new ArrayList<Double>();
do {
double lengte = getLength("Geef de lengte in Meters:");
double gewicht = getGewicht("Geef het gewicht in Kg:");
BMICalculator bmi = new BMICalculator(lengte, gewicht);
bmi.setBmi(bmi.calculateBMI());
bmilist.add(bmi);
for(double i = 0;i < bmilist.size(); i++){
//System.out.println(i);
JOptionPane.showMessageDialog(null, "List:" + i);
}
JOptionPane.showMessageDialog(null, "Bmi: " + String.format("%s", bmi.toString()));
} while(getUserAnswer() == 'J');
}
public static double getLength(String message){
String lengte = JOptionPane.showInputDialog(message);
return Double.parseDouble(lengte);
}
public static double getGewicht(String message){
String gewicht = JOptionPane.showInputDialog(message);
return Double.parseDouble(gewicht);
}
public static char getUserAnswer(){
String answer = JOptionPane.showInputDialog("Wil je opnieuw: j/n?");
return Character.toUpperCase(answer.charAt(0));
}
}
I cant get anything print out of that list. Every time someone calculates his BMI, it should put them in an Arraylist and when they click "continue", no... then it should return all the BMI's they calculated.

You misused a loop with a list structure
for (int i = 0; i < bmilist.size(); i++) {
JOptionPane.showMessageDialog(null, "List:" + bmilist.get(i).getBmi());
}

Try the for loop with int variable
do {
double lengte = getLength("Geef de lengte in Meters:");
double gewicht = getGewicht("Geef het gewicht in Kg:");
BMICalculator bmi = new BMICalculator(lengte, gewicht);
bmi.setBmi(bmi.calculateBMI());
bmilist.add(bmi);
// int variable instead of double inside for loop
for(int i = 0;i < bmilist.size(); i++){
JOptionPane.showMessageDialog(null, "List:" + bmilist.get(i));
}
}while(getUserAnswer() == 'J');

ArrayList<BMICalculator> bmilist = new ArrayList<>();
do {
double lengte = getLength("Geef de lengte in Meters:");
double gewicht = getGewicht("Geef het gewicht in Kg:");
BMICalculator bmi = new BMICalculator(lengte, gewicht);
bmi.setBmi(bmi.calculateBMI());
bmilist.add(bmi);
JOptionPane.showMessageDialog(null, String.format("%s", bmi.toString()));
} while(getUserAnswer() == 'J');
System.out.println("Lengte Gewicht BMI");
for(int i = 0;i < bmilist.size(); i++)
{ System.out.printf("%-10s%-10s%s\n",bmilist.get(i).getLengte(),bmilist.get(i).getGewicht(),String.format("%.2f", bmilist.get(i).getBmi()));
}
}

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

Method returns wrong value in main class

Whenever I run InschrijvingApplicatie, I get a wrong value out of line System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes); because the int should be "10" when I enter 'p' in this line
System.out.printf("Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
I'm supposing there is something wrong at the line int maxBroodjes = (inschrijving.geefAantalPersonen() * 5); but can't seem to figure out what.
How the output should look like
The excercise is: for a company that is inviting employees ('w' in the code), employee with a partner ('p') and guests ('g') and letting them fill in their name, what sort of visitor (employee + partner, guest or employee) they are, then asking how many sandwiches the person wants (guest and employee can max require 5 sandwiches, employee+partner can request 10) and the max value is shown in the integer (max %d). All of this is in a loop until the user writes "no" (but the first char is used => resulting in 'n') when asked "Zijn er nog inschrijvingen", and if the answer is yes, it repeats.
Inschrijving.java
package domein;
public class Inschrijving {
private String naam;
private char categorie;
private int aantalBroodjes;
public Inschrijving(String naam, char categorie) {
setNaam(naam);
setCategorie(categorie);
}
public String getNaam() {
return naam;
}
private void setNaam(String naam) {
this.naam = naam;
}
public char getCategorie() {
return categorie;
}
private void setCategorie(char categorie) {
if (categorie == 'w' || categorie == 'p' || categorie == 'g') {
this.categorie = categorie;
} else {
this.categorie = 'g';
}
}
public int getAantalBroodjes() {
return aantalBroodjes;
}
public void setAantalBroodjes(int aantalBroodjes) {
if (aantalBroodjes <= (geefAantalPersonen() * 5)) {
this.aantalBroodjes += aantalBroodjes;
} else {
this.aantalBroodjes += (geefAantalPersonen() * 2);
}
}
public int geefAantalPersonen() {
switch (categorie) {
case 'w':
case 'g':
return 1;
default:
return 2;
}
}
}
InschrijvingApplicatie
package ui;
import domein.Inschrijving;
import java.util.Scanner;
public class InschrijvingApplicatie {
public static void main(String[] args) {
Scanner invoer = new Scanner(System.in);
String antwoord;
char eersteLetter;
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.nextLine();
eersteLetter = antwoord.toLowerCase().charAt(0);
String naam = null;
String categorie;
char categorieEersteLetter = 0;
int werknemer = 0;
int werknemerMetPartner = 0;
int gast = 0;
int aantalBroodjes;
int tijdelijk;
Inschrijving inschrijving = new Inschrijving(naam, categorieEersteLetter);
if (eersteLetter != 'n') {
do {
System.out.println("Wie mag ik inschrijven? ");
naam = invoer.next();
do {
System.out.printf("Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
categorie = invoer.next();
categorieEersteLetter = categorie.toLowerCase().charAt(0);
switch (categorieEersteLetter) {
case 'w':
werknemer++;
break;
case 'p':
werknemerMetPartner++;
break;
case 'g':
gast++;
break;
}
} while (categorieEersteLetter != 'w' && categorieEersteLetter != 'p' && categorieEersteLetter != 'g');
int maxBroodjes = (inschrijving.geefAantalPersonen() * 5);
do {
System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes);
tijdelijk = invoer.nextInt();
} while (tijdelijk > maxBroodjes);
aantalBroodjes = tijdelijk;
inschrijving.setAantalBroodjes(aantalBroodjes);
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.next();
eersteLetter = antwoord.toLowerCase().charAt(0);
} while (eersteLetter != 'n');
}
System.out.printf("Er komen %d werknemer(s) zonder partner, %d werknemer(s) met partner en %d gast(en) naar de receptie. Er dienen %d broodjes besteld te worden.", werknemer, werknemerMetPartner, gast, inschrijving.getAantalBroodjes());
}
}
There are some problems with your approach, it may work but you shouldn't do that way.
First, you store the total sandwiches requested for all invited peopled in only one Inschrijving object, it make no sense! (Do I need to know the total sandwiches requested or only ones requested by me?). So, change setAantalBroodjes in your Inschrijving class to :
public void setAantalBroodjes(int aantalBroodjes) {
this.aantalBroodjes = aantalBroodjes;
}
Second, The requirement is take a list of people and do something with them, so you should consider use a data structure support you store a list of people like an Array or an ArrayList, then you can do whatever you want with your data once user stop input (eersteLetter == 'n' in your case).
List<Inschrijving> inschrijven = new ArrayList<>();
try (Scanner invoer = new Scanner(System.in)) { // http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html
System.out.println("Zijn er nog inschrijvingen? ");
String antwoord = invoer.nextLine();
char eersteLetter = antwoord.toLowerCase().charAt(0);
while (eersteLetter != 'n') {
Inschrijving inschrijving = null;
System.out.println("Wie mag ik inschrijven? ");
String naam = invoer.nextLine();
char categorieEersteLetter = 0;
do {
System.out.printf(
"Tot welke categorie behoort u?\nTyp w voor een werknemer, p voor een werknemer met partner, g voor een gast: ");
String categorie = invoer.nextLine();
categorieEersteLetter = categorie.toLowerCase().charAt(0);
} while (categorieEersteLetter != 'w' && categorieEersteLetter != 'p' && categorieEersteLetter != 'g');
inschrijving = new Inschrijving(naam, categorieEersteLetter);
int maxBroodjes = (inschrijving.geefAantalPersonen() * 5);
int tijdelijk;
do {
System.out.printf("Hoeveel broodjes wil je bestellen? (max %d) ", maxBroodjes);
tijdelijk = invoer.nextInt();
invoer.nextLine(); // https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo
} while (tijdelijk > maxBroodjes);
inschrijving.setAantalBroodjes(tijdelijk);
inschrijven.add(inschrijving);
System.out.println("Zijn er nog inschrijvingen? ");
antwoord = invoer.nextLine();
eersteLetter = antwoord.toLowerCase().charAt(0);
}
}
When the user finished their input:
// Do stuffs with your list of people here
int werknemer = 0;
int werknemerMetPartner = 0;
int gast = 0;
int aantalBroodjes = 0;
for (Inschrijving inschrijving : inschrijven) {
char categorie = inschrijving.getCategorie();
switch (categorie) {
case 'w':
werknemer++;
break;
case 'p':
werknemerMetPartner++;
break;
case 'g':
gast++;
break;
}
aantalBroodjes += inschrijving.getAantalBroodjes();
}
System.out.printf(
"Er komen %d werknemer(s) zonder partner, %d werknemer(s) met partner en %d gast(en) naar de receptie. Er dienen %d broodjes besteld te worden.",
werknemer, werknemerMetPartner, gast, aantalBroodjes);
Because you are new to java, I use a foreach loop here to make example, after learning about OOP and familiar with java, I suggest you reaserch Java 8 Stream api and lambda expression to work with collection types.

2 instance variables constantly updating each other

I'm having a slight problem where my instance variables kinda work as class variables at least thats what i think.
public class Lab10 {
public static void main(String[] args) {
CannonSolution MaxRange = MAXRMHC(10);
MaxRange.println();
}
public static CannonSolution MAXRMHC(int iter){
double range =0;
double newrange;
CannonSolution sol = new CannonSolution(1,1);
CannonSolution NewSol = new CannonSolution(sol.SendCanang(),sol.SendCanvel());
range = Cannon.GetMaxRange(sol.SendCanang(),sol.SendCanvel());
for(int i =0;i<iter;i++){
NewSol.smallChange();
newrange = Cannon.GetMaxRange(NewSol.SendCanang(), NewSol.SendCanvel());
if(range <= newrange){
System.out.println(range+" is smaller than "+newrange);
NewSol.println();
range = newrange;
sol = NewSol;
}else if (range > newrange){
NewSol.println();
sol.println();
}else{
System.out.println("I don't work");
}
}
System.out.println();
System.out.println(range);
return (sol);
}
}
public class CannonSolution {
private double canang;
private double canvel;
public CannonSolution(double ang, double vel){
if(ang <25.0 || ang >55.0){
canang = Randomang();
}else{
canang = ang;
}
if(vel <1500.0 || vel > 1650.0){
canvel = Randomvel();
}else{
canvel = vel;
}
}
public double SendCanang(){
return (canang);
}
public double SendCanvel(){
return (canvel);
}
private static double Randomang(){
double ang = RandomNumber.RandomNum(25,55);
return ang;
}
private static double Randomvel(){
double vel = RandomNumber.RandomNum(1500,1650);
return vel;
}
private void smallChangeVel(){
double vel = canvel;
double number = (double) RandomNumber.UI(1,30);
double updown = RandomNumber.UI(1,2);
if(updown ==1 ){
vel = vel + number;
}else{
vel = vel - number;
}
if(vel <1500){
vel =1500.0;
}else if (vel > 1650){
vel = 1650.0;
}
canvel = vel;
}
private void smallChangeAng(){
double ang = canang;
double number = RandomNumber.UI(1,3);
double updown = RandomNumber.UI(1,2);
if(updown ==1 ){
ang = ang + number;
}else{
ang = ang - number;
}
if(ang <25){
ang =25.0;
}else if (ang > 55){
ang = 55.0;
}
canang= ang;
}
public void smallChange(){
double updown = RandomNumber.UI(1,2);
if(updown == 1){
smallChangeAng();
}else{
smallChangeVel();
}
}
public void print()
{
System.out.println(canang);
System.out.print(canvel);
}
public void println()
{
print();
System.out.println();
}
}
http://pastebin.com/zJWPyz7Q
http://pastebin.com/EYugr96p
The problem is that when Newsol is changed using the smallchange method it changes both newsol and sol. I've been stuck on this for a while.
Sorry, I wasn't too sure how to format this im new to asking in stackoverflow.
After the line
sol = Newsol;
you have discarded the old object referenced by sol and now both variables sol and Newsol identify the same object. This would lead to the behavior you are seeing.

Setting instance Variable, before creating an object

So i got this program which sets subject, and grades it.
now i got this piece of code:
package ectsmonitor;
import java.util.Scanner;
import java.util.stream.IntStream;
/**
*
* #author JasperF
*/
public class ECTSMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak = new String[aantalvakken];
private Scanner input = new Scanner(System.in);
private int[] ECTS = new int[aantalvakken];
private double[] Cijfer = new double[aantalvakken];
private int totaalECTS;
/**
* #param args the command line arguments
*/
/**
* Asks for amount of Subjects, and sets instance variable for size of
* Arrays
*/
public void setSubjects() {
//System.out.println("Hoeveel vakken heb je?");
//aantalvakken = input.nextInt();
System.out.println(vak.length);
for (int x = 0; x < getAantalvakken(); x++) {
System.out.println("Voer de naam in van je vak!");
vak[x] = input.next();
System.out.println("Voer het aantal punten in voor " + vak[x]);
ECTS[x] = input.nextInt();
System.out.println("Vak Toegevoegd!!");
}
}
public void setCijfer() {
for (int x = 0; x < vak.length; x++) {
System.out.println("Wat is je Cijfer voor " + vak[x] + "?");
Cijfer[x] = input.nextDouble();
System.out.println("Voor het vak " + vak[x] + "heb je als cijfer ingevuld " + Cijfer[x]);
}
}
public void Checkscore() {
for (int x = 0; x < vak.length; x++) {
if (Cijfer[x] >= voldoende) {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: " + ECTS[x]);
} else {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: 0");
}
}
}
public void BAS() {
totaalECTS = IntStream.of(ECTS).sum();
if (totaalECTS < (totaalECTS * (5 / 6))) {
System.out.println("PAS OP!!: Je ligt op schema voor een BAS!");
} else {
System.out.println("Gefeliciteerd!!: Je bent op weg naar je Propodeuse!!");
}
}
/**
* #return the aantalvakken
*/
public int getAantalvakken() {
return aantalvakken;
}
/**
* #param aantalvakken the aantalvakken to set
*/
public void setAantalvakken(int aantalvakken) {
this.aantalvakken = aantalvakken;
}
}
and i got this piece of code to run it:
public class Run {
/**
*
* #author JasperF
* #param args
*/
public static void main(String[] args) {
ECTSMonitor mon = new ECTSMonitor();
mon.setSubjects();
mon.setCijfer();
mon.Checkscore();
mon.BAS();
}
}
now in the first code, the lenght of the arrays is set by the variable 'aantalvakken',
but when i run my program, and print the lenght of te array it says 0.
how can i set the variable aantalvakken to set the array length
Pass aantalvakken value to constructor. And create ArrayList's depends on aantalvakken at constructor.
public class ECSTMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak;
private Scanner input = new Scanner(System.in);
private int[] ECTS;
private double[] Cijfer;
private int totaalECTS;
public ECSTMonitor(int aantalvakken) {
this.aantalvakken = aantalvakken;
vak = new String[aantalvakken];
ECTS = new int[aantalvakken];
Cijfer = new double[aantalvakken];
}
private int aantalvakken;
is not initialized and therefore 0 by default.
try using static variables like below, initialize the variable(aantalvakken) how much array length you want.
public static final int aantalvakken;
or
public static final int aantalvakken=10;

calculating with java with two file program

I have a question on how to calculate with java. In my case, I think I am doing the calculations right, but when I run it, I get a few 0s and some absurd number. How can I fix this? Any help will be greatly appreciated. Below is my code:
public class CO2Footprint {
private int NumberOfPeople, CO2PerPerson, lightBulbs, months;
private double TotalEmission, ReductionPerPaper, ReductionPerPlastic,
ReductionPerGlass, ReductionPerCan, TotalReduction,
FamilyNetEmission, annualGasoline, electricityBill
, lightBulbsRecycled, annualFuelUse, averageMonthlyCostElec,
emissionFactor, monthlyCostSeptElec, monthlyCostOct, monthlyCostNov,
averagePricePerKilowatt, totalWaste, elecPrice, NetEmission;
private boolean paper, plastic, glass, can;
CO2Footprint(int numPeople, boolean bpaper, boolean bplastic, boolean
bglass, boolean bcans, double annuallGasoline
, double electricityyPrice, int lighttBulbs){
NumberOfPeople = 0;
paper = bpaper;
plastic = bplastic;
glass = bglass;
can = bcans;
ReductionPerPaper = 184;
CO2PerPerson = 1018;
ReductionPerPlastic = 25.6;
ReductionPerGlass = 46.6;
ReductionPerCan = 165.8;
TotalEmission = 0;
annualGasoline = 16.5;
electricityBill = 0;
lightBulbs = 10;
lightBulbsRecycled = 0;
annualFuelUse = 0;
averageMonthlyCostElec = 0;
emissionFactor = 1.37;
monthlyCostSeptElec = 551.51;
monthlyCostOct = 392.84;
monthlyCostNov = 445.42;
months = 12;
averagePricePerKilowatt = 4.83;
totalWaste = 0;
NetEmission = 0.0;
}
// method for calculating total emission
public double totalEmission(){
TotalEmission = NumberOfPeople * CO2PerPerson;
return TotalEmission;
}
// method for calculating CO2 reduction
public double reduction(){
TotalReduction = 0;
ReductionPerPaper = 0;
ReductionPerPlastic = 0;
ReductionPerGlass = 0;
ReductionPerCan = 0;
if(paper = true){
ReductionPerPaper = 184;
}else{
ReductionPerPaper = 0;
}
if(plastic = true){
ReductionPerPlastic = 25.6;
}else{
ReductionPerPlastic = 0;
}
if(glass = true){
ReductionPerGlass = 46.6;
}else{
ReductionPerGlass = 0;
}
if(can = true){
ReductionPerCan = 165.8;
}else{
ReductionPerCan = 0;
}
TotalReduction = ReductionPerPaper + ReductionPerPlastic +
ReductionPerGlass + ReductionPerCan + (lightBulbs * 1.37 * 73);
return TotalReduction;
}
public double calcAnnualFuelUseGallonCO2(){
annualFuelUse = annualGasoline * 12 * 12;
return annualFuelUse;
}
public double calcElectricityBill(){
return (averageMonthlyCostElec / averagePricePerKilowatt) * emissionFactor * months;
}
public double electrictyPrice(){
return averagePricePerKilowatt;
}
public double calcWaste(){
TotalReduction = 0;
ReductionPerPaper = 0;
ReductionPerPlastic = 0;
ReductionPerGlass = 0;
ReductionPerCan = 0;
if(paper = true){
ReductionPerPaper = 184;
}else{
ReductionPerPaper = 0;
}
if(plastic = true){
ReductionPerPlastic = 25.6;
}else{
ReductionPerPlastic = 0;
}
if(glass = true){
ReductionPerGlass = 46.6;
}else{
ReductionPerGlass = 0;
}
if(can = true){
ReductionPerCan = 165.8;
}else{
ReductionPerCan = 0;
}
totalWaste = ReductionPerPaper + ReductionPerPlastic +
ReductionPerGlass + ReductionPerCan;
return totalWaste;
}
public double calcBulbsEmissionReduction(){
return lightBulbs * 1.37 * 73;
}
public double calcNetEmission(){
NetEmission = TotalEmission - CO2PerPerson;
return NetEmission;
}
}
If it helps, below is the code for how I called the methods:
import java.util.ArrayList;
public class CO2FootprintTester {
public static void main(String args[]){
ArrayList<CO2Footprint> CO2 = new ArrayList<CO2Footprint>();
CO2.add(new CO2Footprint(1, true, true, true, true, 16.5, 4.83, 10));
CO2Footprint data;
for(int i = 0; i < CO2.size(); i++){
data = CO2.get(i);
data.calcAnnualFuelUseGallonCO2();
data.calcBulbsEmissionReduction();
data.calcElectricityBill();
data.calcWaste();
data.electrictyPrice();
data.reduction();
data.totalEmission();
}
// create table
System.out.println("___________________________________________________"
+ "_____________________________________________________________________________");
System.out.printf("%65s%44s%n", " Pounds of CO2 Emitted From: |",
" Pounds of CO2 Reduced From: ");
System.out.println("___________________________________________________"
+ "_____________________________________________________________________________");
System.out.printf("%1s%25s%25s%25s%25s%n%n", "Gas", "Electricity",
"Waste", "Recycling", "New Bulbs");
// call methods
for(int i = 0; i < CO2.size(); i++){
data = CO2.get(i);
System.out.printf("%5.5f%15.5f%15.5f%15.5f%15.5f", data.calcAnnualFuelUseGallonCO2(), data.calcElectricityBill(),
data.totalEmission(), data.calcNetEmission(), data.calcBulbsEmissionReduction());//,
//data.calcElectricityBill(), data.totalEmission(), data.calcNetEmission(),
//data.calcBulbsEmissionReduction());
}
}
}
Seems like you are facing the problem of using double data type precision. double data type is sometimes troublesome in precision calculations like monetary values etc.
It is recommended to use BigDecimal to ensure precision while arithmetic operations.
More information can be found at this post

Categories