I try to change the values of coupe but the output doesn't change. In NetBeans, I saved these two programs under the same project and package. I did not include it here because it may have made the code too long, but I also wrote accessor methods which work fine, so I am confused as to why the mutator methods don't work.
Class code:
package auto;
public class Auto
{
private String model;
private int milesDriven;
private double gallonsOfGas;
public Auto(String startModel,
int startMilesDriven,
double startGallonsOfGas)
{
model = startModel;
setMilesDriven(startMilesDriven);
setGallonsOfGas(startGallonsOfGas);
}
public void setModel(String newModel)
{
model = newModel;
}
public void setMilesDriven(int newMilesDriven)
{
if (newMilesDriven >= 0)
milesDriven = newMilesDriven;
else
{
System.err.println("Miles driven cannot be negative.");
System.err.println("Value not changed.");
}
}
public void setGallonsOfGas(double newGallonsOfGas)
{
if (newGallonsOfGas >= 0.0)
gallonsOfGas = newGallonsOfGas;
else
{
System.err.println("Gallons of gas cannot be negative.");
System.err.println("Value not changed.");
}
}
}
Client class code:
package auto;
import java.text.DecimalFormat;
public class AutoClient
{
public static void main(String [] args)
{
DecimalFormat milesPattern = new DecimalFormat("#,###");
Auto coupe = new Auto("Corvette", 300000, 0.0);
String coupeModel = coupe.getModel();
int coupeMiles = coupe.getMilesDriven();
double coupeGallons = coupe.getGallonsOfGas();
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
}
}
Given your current code, after you changed the values
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
You need to get them again
coupeModel = coupe.getModel();
coupeMiles = coupe.getMilesDriven();
coupeGallons = coupe.getGallonsOfGas();
Before you can call
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
I suggest you update Auto and add a toString()
#Override
public String toString() {
return "coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons;
}
Then you can replace (in both places)
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
With
System.out.println(coupe); // <-- Java will call toString() for you
Related
I'm writing a program that creates a new student with his own ID. And after that I want to check by id does a student exists. What I am doing wrong right now? Because all the time only else statement works.
ArrayList<Studentas> studentuSarasas = new ArrayList<Studentas>();
protected int studentoID;
protected String studentoVardas;
protected String studentoPavarde;
protected String pirmasDalykas;
protected String antrasDalykas;
protected String treciasDalykas;
protected String ketvirtasDalykas;
protected String penktasDalykas;
protected int pirmoPaz;
protected int antroPaz;
protected int trecioPaz;
protected int ketvirtoPaz;
protected int penktoPaz;
Studentas() {
}
public Studentas(int studentoID, String studentoVardas, String studentoPavarde, String pirmasDalykas, String antrasDalykas, String treciasDalykas, String ketvirtasDalykas, String penktasDalykas, int pirmoPaz, int antroPaz, int trecioPaz, int ketvirtoPaz, int penktoPaz) {
this.studentoID = studentoID;
this.studentoVardas = studentoVardas;
this.studentoPavarde = studentoPavarde;
this.pirmasDalykas = pirmasDalykas;
this.antrasDalykas = antrasDalykas;
this.treciasDalykas = treciasDalykas;
this.ketvirtasDalykas = ketvirtasDalykas;
this.penktasDalykas = penktasDalykas;
this.pirmoPaz = pirmoPaz;
this.antroPaz = antroPaz;
this.trecioPaz = trecioPaz;
this.ketvirtoPaz = ketvirtoPaz;
this.penktoPaz = penktoPaz;
}
#Override
public String toString() {
return "Studento numeris: " + studentoID +
", Vardas: " + studentoVardas +
", Pavarde: " + studentoPavarde +
", Pasirenkamas dalykas: " + pirmasDalykas +
", Pasirenkamas dalykas: " + antrasDalykas +
", Pasirenkamas dalykas: " + treciasDalykas +
", Pasirenkamas dalykas: " + ketvirtasDalykas +
", Pasirenkamas dalykas: " + penktasDalykas +
", Pirmojo dalyko pazymys: " + pirmoPaz +
", Antrojo dalyko pazymys: " + antroPaz +
", Treciojo dalyko pazymys: " + trecioPaz +
", Ketvirtojo dalyko pazymys: " + ketvirtoPaz +
", Penktojo dalyko pazymys: " + penktoPaz;
}
Here's how I create my student:
private void studentoSukurimas() {
System.out.println("ID, name, surn, studthing1- studthing5 ,averages from 1 to 5");
Scanner SI = new Scanner(System.in);
String[] iveda = SI.nextLine().split(" ");
studentuSarasas.add(new Studentas(Integer.parseInt(iveda[0]), iveda[1], iveda[2], iveda[3], iveda[4], iveda[5], iveda[6], iveda[7], Integer.parseInt(iveda[8]), Integer.parseInt(iveda[9]), Integer.parseInt(iveda[10]), Integer.parseInt(iveda[11]), Integer.parseInt(iveda[12])));
System.out.println("gut");
Pasirinkimai();
}
And this is my code where I check does the student by ID exists:
private void studentasPagalId() {
System.out.println("student id");
Scanner SI = new Scanner(System.in);
int userSelects = Integer.parseInt(SI.nextLine());
String q = Integer.toString(userSelects);
if(q.equals(getStudentoID())) {
System.out.println("+");
} else {
System.out.println("-");
}
Pasirinkimai();
}
if you try to check every element of a list, you can use a for.
for(int i=0; i<studentuSarasas.size();i++){
if(q.equals(studentuSarasas.get(i).getStudentoID()))
...
}
I made an ArrayList inside public static void main(String[] args)
With the following code:
ArrayList<kistenEigenschaften> kisten = new ArrayList<kistenEigenschaften>(75);
kistenEigenschaften is properly defined in its own class.
But now I want to call that ArrayList in the folowwing method:
public static void kistenListe() {
System.out.println("Sie haben " + kisten.size() + " kisten am lager.");
for (int i = 0; i < kisten.size(); i++) {
System.out.println("Kiste NR: " + kisten.get(i).getidNr() + ". Größe ist " + kisten.get(i).getBreite() + " cm breit " + kisten.get(i).getLänge() + " cm lang " + kisten.get(i).getHöhe() + " cm Höhe.");
}
}
Outside of main()
But cant seem to be able to call that arraylist outside main()
Tried the search function and could not find any solution, sorry if it was already mentioned.
You have two possible Solutions:
First: Add the list as patameter:
public static void main(String[] args) {
ArrayList<kistenEigenschaften> kisten = new ArrayList<kistenEigenschaften>(75);
....
kistenListe(kisten);
}
public static void kistenListe(List<kistenEigenschaften> kisten) {
System.out.println("Sie haben " + kisten.size() + " kisten am lager.");
for (int i = 0; i < kisten.size(); i++) {
System.out.println("Kiste NR: " + kisten.get(i).getidNr() + ". Größe ist " + kisten.get(i).getBreite() + " cm breit " + kisten.get(i).getLänge() + " cm lang " + kisten.get(i).getHöhe() + " cm Höhe.");
}
}
second: Declare kisten as a class property:
ArrayList<KistenEigenschaften> kisten
public static void main(String[] args) {
kisten = new ArrayList<KistenEigenschaften>(75);
....
kistenListe();
}
public static void kistenListe() {
System.out.println("Sie haben " + kisten.size() + " kisten am lager.");
for (int i = 0; i < kisten.size(); i++) {
System.out.println("Kiste NR: " + kisten.get(i).getidNr() + ". Größe ist " + kisten.get(i).getBreite() + " cm breit " + kisten.get(i).getLänge() + " cm lang " + kisten.get(i).getHöhe() + " cm Höhe.");
}
}
pay Attention to the Java naming convention. class names should start with upper case character.
Do not use german umlauts in property and method names.
getidNr() should be getIdNr()
I am currently working on a project where I read in a CSV file that contains a list of Pokemon, as well as their traits. I am trying to run a battle simulator that randomly pairs up these Pokemon with each other and compares their combatScore, which is a result of a simple calculation using their traits such as speed, attack, defense, etc. I read in all of the Pokemon from the CSV file into an ArrayList of type Pokemon. Now, I want to randomly pair them up with each other and compare their combatScore; whoever has the higher score moves on to the next round, and the loser is placed into another ArrayList of defeated Pokemon. However, I do not know how to randomly pair up the Pokemon. Here is my code of the main class so far:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class assign1 {
public static void main(String[] args) throws IOException {
String csvFile = args[0]; //path to CSV file
String writeFile = args[1]; //name of output file that contains list of Pokemon and their traits
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Pokemon> population = new ArrayList<Pokemon>();
FileWriter fileWriter = new FileWriter(writeFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
try {
br = new BufferedReader(new FileReader(csvFile));
String headerLine = br.readLine(); // used to read first line of CSV file that contains headers
while ((line = br.readLine()) != null) {
Pokemon creature = new Pokemon();
// use comma as separator
String[] pokemon = line.split(cvsSplitBy);
creature.setId(pokemon[0]);
creature.setName(pokemon[1]);
creature.setType1(pokemon[2]);
creature.setType2(pokemon[3]);
creature.setTotal(pokemon[4]);
creature.setHp(Integer.parseInt(pokemon[5]));
creature.setAttack(Integer.parseInt(pokemon[6]));
creature.setDefense(Integer.parseInt(pokemon[7]));
creature.setSpAtk(Integer.parseInt(pokemon[8]));
creature.setSpDef(Integer.parseInt(pokemon[9]));
creature.setSpeed(Integer.parseInt(pokemon[10]));
creature.setGeneration(Integer.parseInt(pokemon[11]));
creature.setLegendary(Boolean.parseBoolean(pokemon[12]));
creature.getCombatScore();
// Adds individual Pokemon to the population ArrayList
population.add(creature);
// Writes to pokemon.txt the list of creatures
bufferedWriter.write(creature.getId() + ". "
+ "Name: " + creature.getName() + ": "
+ "Type 1: " + creature.getType1() + ", "
+ "Type 2: " + creature.getType2() + ", "
+ "Total: " + creature.getTotal() + ", "
+ "HP: " + creature.getHp() + ", "
+ "Attack: " + creature.getAttack() + ", "
+ "Defense: " + creature.getDefense() + ", "
+ "Special Attack: " + creature.getSpAtk() + ", "
+ "Special Defense: " + creature.getSpDef() + ", "
+ "Speed: " + creature.getSpeed() + ", "
+ "Generation: " + creature.getGeneration() + ", "
+ "Legendary? " + creature.isLegendary() + ", "
+ "Score: " + creature.getCombatScore());
bufferedWriter.newLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
bufferedWriter.close();
}
}
And here is the code for my Pokemon class:
public class Pokemon {
String id;
String name;
String type1;
String type2;
String total;
int hp;
int attack;
int defense;
int spAtk;
int spDef;
int speed;
int generation;
boolean legendary;
public Pokemon() {}
public String getId () {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType1() {
return type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getSpAtk() {
return spAtk;
}
public void setSpAtk(int spAtk) {
this.spAtk = spAtk;
}
public int getSpDef() {
return spDef;
}
public void setSpDef(int spDef) {
this.spDef = spDef;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getGeneration() {
return generation;
}
public void setGeneration(int generation) {
this.generation = generation;
}
public boolean isLegendary() {
return legendary;
}
public void setLegendary(boolean legendary) {
this.legendary = legendary;
}
public int getCombatScore() {
return (speed/2) * (attack + (spAtk/2)) + (defense + (spDef/2));
}
#Override
public String toString() {
return "Name: " + this.getName()
+ ", Type 1: " + this.getType1()
+ ", Type 2: " + this.getType2()
+ ", Total: " + this.getTotal()
+ ", HP: " + this.getHp()
+ ", Attack: " + this.getAttack()
+ ", Defense: " + this.getDefense()
+ ", Sp. Attack: " + this.getSpAtk()
+ ", Sp. Defense: " + this.getSpDef()
+ ", Generation: " + this.getGeneration()
+ ", Legnedary: " + this.isLegendary()
+ ", Score: " + this.getCombatScore();
}
}
I only want to compare their combatScore values to each other. Any help/suggestions would be much appreciated.
What come to my mind is this. You pick one random item (pokemon) from array list. Remove it from array list. Then you pick one random item again and remove it. Now you have a pair of items. Repeat above step for remaining items in array list until no more items available.
Or you can shuffle whole array list first and then pick item i and item i+1 as pair for i=0,2,4,6,...
Collections.shuffle(pokemonsArrayList);
for (int i=0; i< pokemonsArrayList.size(); i+=2) {
pokemon1 = pokemonsArrayList.get(i);
pokemon2 = pokemonsArrayList.get(i+1);
}
Just make sure that number of elements in ArrayList is even. Otherwise code above will throw exception index out of bound
Since every element in an ArrayList has an index, you can just get a random element from it by calling
Pokemon pokemon1;
Pokemon pokemon2;
pokemon1 = arrayList.get(Math.random()*arrayList.size());
do {
pokemon2 = arrayList.get(Math.random()*arrayList.size());
} while(pokemon1.getId() == pokemon2.getId());
then compare the Pokémon you got out of List1 with the one you got from List2.
You can then of course remove the Pokémon from the List if you wish.
Hope that helps you out!
I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}
This is where I am printing out and I need it to print in columns.aLeaderboard is an array list with a custom class.it contains several different ints
System.out.println("Position Team Games Played Home Wins Home Draws Home Losses Home Goals For Home Goals Against Away Wins Away Draws Away Losses Away Goals For Away Goals Against Goal Difference Total Points");
for(int counter = 0;counter<teamName.size();counter++)
{
System.out.print((counter + 1) + " " + teamName.get(counter) + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " " + (aLeaderboard.get(counter)).getHomeWins() + " " + (aLeaderboard.get(counter)).getHomeDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeLosses() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeGoalsFor() + " " + (aLeaderboard.get(counter)).getHomeGoalsAgainst() + " " + (aLeaderboard.get(counter)).getAwayLosses() + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " ");
System.out.print((aLeaderboard.get(counter)).getAwayGoalsFor() + " " + (aLeaderboard.get(counter)).getAwayGoalsAgainst() + " " + (aLeaderboard.get(counter)).getGoalsDifference() + " " + (aLeaderboard.get(counter)).getTotalPoints());
System.out.println();
}
I would use System.out.printf(...) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.
For example:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Foo4 {
public static void main(String[] args) {
List<Bar4> bar4List = new ArrayList<>();
bar4List.add(new Bar4("Donald", 3, "A", 22.42));
bar4List.add(new Bar4("Duck", 100, "B", Math.PI));
bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20)));
String titleTemplate = "%-10s %6s %6s %9s%n";
String template = "%-10s %6d %6s %9s%n";
System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost");
for (Bar4 bar4 : bar4List) {
System.out.printf(template, bar4.getName(),
bar4.getValue(), bar4.getGrade(), bar4.getCostString());
}
}
}
class Bar4 {
private String name;
private int value;
private String grade;
private double cost;
private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
public Bar4(String name, int value, String grade, double cost) {
this.name = name;
this.value = value;
this.grade = grade;
this.cost = cost;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String getGrade() {
return grade;
}
public double getCost() {
return cost;
}
public String getCostString() {
return currencyFormat.format(cost);
}
}
Which would return:
Name Value Grade Cost
Donald 3 A $22.42
Duck 100 B $3.14
Herman 20 C $4.47
For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.