I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
This is the code that is meant to call a class called Couple and yet
it doesn't recognize the class why is this?
public class AgencyInterFace {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int choice, position;
showSelection();
choice = console.nextInt();
while (choice != 9) {
switch (choice) {
case 1:
addCouple();
break;
case 2:
position = console.nextInt();
testCouple(position);
break;
case 3:
position = console.nextInt();
displayCouple(position);
break;
case 9:
break;
default:
System.out.println("Invalid Selection");
} //end switch
showSelection();
choice = console.nextInt();
}
}
public static void showSelection() {
System.out.println("Select and enter");
System.out.println("1 - add a new couple");
System.out.println("2 - test a couple");
System.out.println("3 - display couple");
System.out.println("9 - exit");
}
public static void addCouple() {
Scanner console = new Scanner(System.in);
String herName, hisName;
int herAge, hisAge, ageDiff;
System.out.print("her name: ");
herName = console.nextLine();
System.out.print("her age: ");
herAge = console.nextInt();
System.out.print("his name: ");
hisName = console.nextLine();
System.out.print("his age: ");
hisAge = console.nextInt();
ageDiff = herAge - hisAge;
c.addData(herName, herAge, ageDiff, hisName, hisAge, ageDiff);
}
public static void testCouple(int position) {
System.out.println(c.test(position));
}
public static void displayCouple(int position) {
System.out.println(c.display(position));
}
public static void averageAge(int position) {
System.out.println(c.avgAge());
}
public static void maxDifference(int position) {
System.out.println(c.maxDif(position));
}
public static void averageDifference(int position) {
System.out.println(c.avgDif(position));
}
}//end of class
This code is the class that is meant to be called and that is not
being recognized and is unable to be called.
public class Couple {
final private int MAX = 5;
private Person[] p1, p2;
private int total;
public Couple() {
p1 = new Person[MAX];
p2 = new Person[MAX];
total = 0;
}
private void setData1(Person p, String name, int age, int ageDiff) {
p.setName(name);
p.setAge(age);
}
public String test(int pos) {
if (pos != -1) {
if (p1[pos].getAge() < p2[pos].getAge()) return ("GOOD FOR
"+p2[pos].getName()+" !");
else return ("GOOD
FOR "+p1[pos].getName()+" !");
}
return "error";
}
public void addData(String name1, int age1, int ageDiff1, String
name2, int age2, int ageDiff2) {
p1[total] = new Person();
p2[total] = new Person();
setData1(p1[total], name1, age1, ageDiff1);
setData1(p2[total], name2, age2, ageDiff2);
total++;
}
public String display(int position) {
if (position != -1)
return ("p1: " + p1[position].getName() + "
"+p1[position].getAge()+" / n "+" p2:
"+p2[position].getName()+"
"+p2[position].getAge());
else
return ("error");
}
public String avgAge(int position) {
double avg = 0;
double sum = 0.0;
for (int i = 0; i < position; i++) {
sum += p1[total].getAge();
sum += p2[total].getAge();
}
avg = sum / position;
return ("The average age is: " + avg);
}
public void ageDifference(int position) {
double ageDif = 0.0;
double ageSum = 0.0;
for (int i = 0; i < position; i++) {
if (p1[total].getAge() < p2[total].getAge()) {
ageSum = p2[total].getAge() - p1[total].getAge();
} else {
ageSum = p1[total].getAge() - p2[total].getAge();
}
ageSum = ageDif;
}
}
}
Is this have something to do with the name of the 'Couple' file or how
I call the class. I am getting an 'Undeclared Variable' error.
You defined c inside your main() method. Therefore it is not visible in your other methods. Either pass c as a parameter to your other methods or make it a (static) property of the AgencyInterFace class instead of a local variable of main().
USING STATIC METHODS
If you want to call a method of the class, e.g. test(int position), without creating a variable c, you need to make this method static:
public static String test(int pos) {
if (pos!=-1) {
if (p1[pos].getAge()<p2[pos].getAge()) return("GOOD FOR "+p2[pos].getName()+"!");
else return("GOOD FOR"+p1[pos].getName()+"!");
}
return "error";
}
In this case, your arrays p1[] and p2[] would also need to be static --> they would only be created one time.
And example for making your arrays static:
private static Person[] p1 = new Person[MAX],
p2 = new Person[MAX];
Now you can call this method of the class using Couple.test(position) and it will return a String.
USING NON-STATIC METHODS
If you want to create multiple references of the class Couple, in that p1[] and p2[] should contain different values, you need to create a reference of the class Couple.
You can implement this by telling the program, what c is:
Couple c = new Couple();
Edit:
I see that you have created a couple, but not at the right place. If you create your couple inside of the main() method, you cannot use it anywhere except in this method. You should declare it in your class:
public class AgencyInterFace {
private static Couple c = new Couple(); //<-- here
// main-method
// other methods
}
in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}
i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}
import java.text.DecimalFormat; // For proper currency
import java.util.Arrays;
import java.util.Comparator;
public class Inventory {
public static void main( String args[] )
{
// Start array of software titles
Software[] aSoftware = new Software[4];
aSoftware[0]= new Software("Command and Conquer ", 6, 29.99, 10122);
aSoftware[1]= new Software("Alice in Wonderland", 1, 10.99,10233);
aSoftware[2]= new Software("Doom", 1, 10.99, 10344);
aSoftware[3]= new Software("Walking Dead", 6, 9.99, 10455);
//Set currency format
DecimalFormat money = new DecimalFormat("$0.00");
// Sort in order of Software Name
Arrays.sort(aSoftware, new Comparator<Software>() {
public int compare(Software s1, Software s2) {
return s1.getSoftwareTitle().compareTo(s2.getSoftwareTitle());
}
});
// Display software title, number of units, cost, item number and total inventory
for (int i = 0; i < aSoftware.length; i++){
System.out.println("Software Title is "+ aSoftware[i].getSoftwareTitle() );
System.out.println("The number of units in stock is "+ aSoftware[i].getSoftwareStock() );
System.out.println("The price of the Software Title is "+ (money.format(aSoftware[i].getSoftwarePrice() )));
System.out.println( "The item number is "+ aSoftware[i].getSoftwareNum());
System.out.println( "The year of copyright is "+ aSoftware[i].getYear());
System.out.println( "The restocking fee is "+ aSoftware[i].getRestockingFee());
System.out.println( "The value of the Software Inventory is "+ (money.format(aSoftware[i].Softwarevalue() )));
System.out.println();
}
//output total inventory value
double total = 0.0;
for (int i = 0; i < 3; i++){
total += aSoftware[i].getCalculateInventory();
}
System.out.printf("Total Value of Software Inventory is: \t$%.2f\n", total);
//end output total inventory value
}
} //end main
public class Software
{
// Declare variables
String SoftwareTitle;
int SoftwareStock;
double SoftwarePrice;
int SoftwareNum;
double CalculateInventory;
double SoftwareValue;
double value;
Software( String softtitle, int softstock, double softprice, int softitemnum )
{
// Create object constructor
SoftwareTitle = softtitle;
SoftwareStock = softstock;
SoftwarePrice = softprice;
SoftwareNum = softitemnum;
}
// Set Software Title
public void setSoftwareTitle( String softtitle )
{
SoftwareTitle = softtitle;
}
// Return Software Title
public String getSoftwareTitle()
{
return SoftwareTitle;
}
// Set software inventory
public void setSoftwareStock( int softstock)
{
SoftwareStock = softstock;
}
// Return software inventory
public int getSoftwareStock()
{
return SoftwareStock;
}
// Set software price
public void setSoftwarePrice( double softprice )
{
SoftwarePrice = softprice;
}
// Return software price
public double getSoftwarePrice()
{
return SoftwarePrice;
}
// Set item number
public void setSoftwareNum( int softitemnum )
{
SoftwareNum = softitemnum;
} //
//return software item number
public int getSoftwareNum()
{
return SoftwareNum;
} //
// calculate inventory value
public double Softwarevalue()
{
return SoftwarePrice * SoftwareStock;
}
public void setCalculateInventory (double value){
this.CalculateInventory = value;
}
public double getCalculateInventory(){
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}//end method value
//
public class Project3 extends Software
{
// Unique feature
private int year = 2012;
// Default Constructor
public Project3(String softtitle, int softstock, double softprice,int softitemnum, int year) {
super(softtitle, softstock, softprice, softitemnum);
this.year = year;
}
// Retuen Year
public int getYear()
{
return year;
}
// Set year
public void setYear(int year)
{
this.year = year;
}
// Calculate 5% restocking fee
public double getRestockingFee()
{
return getSoftwarePrice() * getSoftwareStock() * 0.05;
}
public double getCalculateInventory()
{
double value = 0;
for(int i = 0; i < 3; i++){
value = Softwarevalue();
}
return value;
}
}
My program runs fine except I can not get the my System out to pull over the getYear method and the getRestockingFee nethod from my Project 3 subclass. I could use a nudge in the right direction, I have to be missing something crazy.
The Java compiler, when given a Software object, has no way to know that it is really a Project3. In real life, if I put a Granny Smith apple in a box, and I tell you that there is an apple in the box, would you be able to tell me whether it boolean isGreen()? Java has the same problem!
There are possible 3 solutions:
When you construct the object, store it in a Project3 variable (and make sure the constructed type is a Project3!
Tell the JVM: "Hey this is really a Project3!" You can do this by casting the object to the correct time. Syntax ((Project3) mySoftware).getYear()
Define a meaning for the method getYear in the *super*class. This would be like telling you "hey, assume all Apples aren't green (isGreen() returns false)"... but if I know it's a Granny Smith subclass apple, isGreen returns true now!
Your choice of solution depends on what you want your system to do.