Increment an "ID" count without a object with a starting value (java) - java

Everytime I run this program to create a new object it is supposed to start at 1000 and each time it is created increment by one. How do I increment the count of this independant of the count of the array.
Right now each time i run the program it outputs an Id of 1000 for each
Please be as simple as possible I don't understand java that well. thanks
Main program
import javax.swing.JOptionPane;
public class useConcert {
private static Concert[] concert = new Concert[100];
private static int numConcert = 0;
public static void main (String[] args){
String userInput = "";
boolean testResult;
do {
userInput = mainMenu();
if (userInput.equals("1")) {
do{
String artist = getStringInput("Artist or Group name?");
int month = getIntegerInput("Enter month in XX format ");
int day = getIntegerInput("Enter day in XX format ");
int year = getIntegerInput("Enter year in XXXX format");
int ticketCost = getIntegerInput("Enter cost per ticket ($25 - $250)");
int quantTickets = getIntegerInput("Enter Number of tickets available (Max 10,000)");
int concertId = 1000;
concert[numConcert++] = new Concert(artist,quantTickets,ticketCost,month,day,year,concertId);
}while (JOptionPane.showConfirmDialog(null, "Add another concert?")==JOptionPane.YES_OPTION);
} else if (userInput.equals("2")) {
listConcert();
}
} while (!userInput.equals("0"));
public static String concertList(){
String outputString = "";
for (int idx =0; idx < numConcert; idx++){
outputString += concert[idx].shortString() + "\n";
}
return outputString;
}
public static void listConcert() {
EZJ.dialog(concertList());
}
}
Class
public class Concert {
private String artist = "";
private int quantTickets = 0;
private int ticketCost = 0;
private int month = 0;
private int day = 0;
private int year = 0;
private int numConcert = 0;
private int concertId = 1000;
public Concert(String artist, int quantTickets, int ticketCost, int month, int day, int year, int concertId){
this.artist = artist;
this.quantTickets = quantTickets;
this.ticketCost = ticketCost;
this.month = month;
this.day = day;
this.year = year;
this.concertId = concertId;
}
public void setConcertId (int concertId){
concertId++;
this.concertId = concertId;
}
public String shortString(){
return " " + artist + " " + getConcertId();
}

There is no reason to keep the concert ID separate from the array count. In fact, the array count would be a very good concert ID. You would just have to modify this line to read:
concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);

Related

League Scheduling program, inserting dates correctly

Having some problems with this program. I am new to Java and am trying to make a league scheduler. I have got to the point where the user can enter a number of teams needed, expected league start date and end date. Once the user selects the end date, a number of rounds are suggested to the user as this would be the number of weeks the league would need to go on for. Currently though, when the league generates, the dates print altogether, my question is how can I can the dates to print like - "round 1 05/06/2018". Also, how can I change my program so an odd number can be accepted, similar to a 'bye'?
I apologise for my ill knowledge of the subject, I have included a snippet of my code and a picture of my GUI so it gives more context.
Many thanks,
Jack
void cyclicRoll(int cycle[], int teams) {
int tmp = cycle[1];
for(int i=1;i<teams-1;i++) {
int pr = cycle[i+1];
cycle[i+1] = tmp;
tmp = pr;
}
cycle[1] = tmp;
}
void scheduleTournament(int teams, int round) {
if (((teams%2 != 0) && (round != teams - 1))||(teams <= 0))
throw new IllegalArgumentException();
int[] cycle = new int[teams];
int n = teams /2;
for (int i = 0; i < n; i++) {
cycle[i] = i + 1;
cycle[teams - i - 1] = cycle[i] + n;
}
Date startDate = (jXDatePicker1.getDate());
Date endDate = (jXDatePicker2.getDate());
LocalDate dates = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstdate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
DayOfWeek dayOfWeeek = dates.getDayOfWeek();
LocalDate datee = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
String listrep ="";
String firstDateToPrint = firstdate.toString();
while (!dates.equals(datee)) {
jTextArea1.removeAll();
if(dayOfWeeek == dayOfWeeek) {
dates = dates.plusDays(7);
}
String[] Itdates = {dates.toString()
};
for(String replacement : Itdates) {
if ("".equals(listrep)) {
listrep += replacement;
} else {
listrep += ", \n" + replacement ;
}
}
}
jTextArea1.append(firstDateToPrint + "\n");
jTextArea1.append(listrep);
for(int d = 1; d <= round; d++)
{
jTextArea1.append(String.format("Round %d\n", d ));
for (int i = 0; i < n; i++)
{
jTextArea1.append(String.format("team %d - team %d\n",cycle[i],cycle[teams - i - 1]));
}
//Roll the cycle keeping the first constant
cyclicRoll(cycle,teams);
}
}
String ref;
String teams;
String rounds;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.selectAll();
jTextArea1.replaceSelection("");
teams = jTextField1.getText();
int teamsToEnter = Integer.parseInt(teams);
rounds = jTextField2.getText();
int roundsToEnter = Integer.parseInt(rounds);
ref = jTextField3.getText();
jTextArea1.append("Ref "+ref + "\n");
scheduleTournament(jTextField2,roundsToEnter);
}

Printing the value and position of an array from a method

I am working on a program that takes user input for an array. One method I have FindLowestTempInArray returns the lowestDay (the position in the array). I want to print the index and the value at that spot in my main method. I have been searching and I dont know a simple way to do this. Right now I have been just been printing the data from the methods without returning the values. That works but I want to know how to print the values from the main. So once again all I am wondering is how to print both the lowestTemp and the lowestDay from the method in the main.
Here is my code I have:
public static int FindLowestTempInArray(int[] T)
{
// Returns the index of the lowest temperature in array T
int lowestTemp = Uninitialized;
int lowestDay = 0;
for(int day = 0; day < T.length; day++)
{
if(T[day] != Uninitialized && ( T[day] < lowestTemp || lowestTemp == Uninitialized))
{
lowestTemp = T[day];
lowestDay = day;
return lowestTemp;
}
}
return lowestDay;
}
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] high = new int[32];
int [] low = new int[32];
Init (high);
Init(low);
LoadData(high,low);
Report(high, low);
FindAvg(high);
//FindAvg(low);
//why do i not need to do both the one above and FindAvg(low);
System.out.println("The average for the high is: " + FindAvg(high));
System.out.println("The average for the low is: " + FindAvg(low));
//Lowest(high, low);
FindLowestTempInArray(high);
System.out.println(FindLowestTempInArray(high) + "\n" + FindLowestTempInArray(low));
Highest(high,low);
System.out.println("\n" + "The highest high is: " + Highest(high, low) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(high, low));
System.out.println("\n" + "The highest low is: " + Highest(low, high) + " degrees." + "\n" +
"This temperature was recorded on day: " + Highest(low, high));
// LeastToGreatest(high, low);
}
There are 2 ways:
Change the return type of your FindLowestTempInArray to int[] i.e integer array and say int[0] islowest temperature and int[1] is lowest day
you can create a new class say Temperature with 2 class variables say temperature and day, and in your method FindLowestTempInArray you can have return type of Temperature and you can set the Temperature object in that method.
Below is sample of return type int[].
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
int[] lowest = new int[2];
lowest = FindLowestTempInArray(low);
System.out.println(lowest[0] + " " + lowest[1]);
}
public static int[] FindLowestTempInArray(int[] T) {
int[] lowest = new int[2];
lowest[0] = Uninitialized;
lowest[1] = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < lowest[0] || lowest[0] == Uninitialized)) {
lowest[0] = T[day];
lowest[1] = day;
}
}
return lowest;
}
}
Solution 2(Inner Class):
public class Weather {
private static final int Uninitialized = -999;
public static void main(String[] args) {
int[] low = new int[args.length];
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
low[i] = Integer.parseInt(args[i]);
}
System.out.println("\n");
Weather.Temperature temp = FindLowestTempInArray(low);
System.out.println(temp.temperature + " " + temp.day);
}
public static Weather.Temperature FindLowestTempInArray(int[] T) {
Weather.Temperature temp=new Weather.Temperature();
temp.temperature = Uninitialized;
temp.day = 0;
for (int day = 0; day < T.length; day++) {
if (T[day] != Uninitialized
&& (T[day] < temp.temperature || temp.temperature == Uninitialized)) {
temp.temperature = T[day];
temp.day = day;
}
}
return temp;
}
static class Temperature{
private int temperature;
private int day;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
}
One way would be to change the return type of public static int FindLowestTempInArray(int[] T) to int[], so that you can return both values. Otherwise, as soon as one return statement is executed, the method is exited.
You can use lowest[0] for the day and lowest[1] for the temp, or vice versa.
Another way is to get these two values separately (using parameters to distinguish which return value you want) and store them in two variables. The idea is to get these values stored somewhere in the main method to be able to play with them.
After you do that, you can use System.out to display the values, as desired.

Need help using an ArrayList

It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}

Need assistance with attributes in Java

What I'm trying to do is access an object, in this case date1 which has 3 attributes day, month and year. I'm attempting to make a method called showTomorrow() which will display the objects information 1 day infront in String format. This means I cannot alter the attributes of the original object.
I've written the Data.java program and it's shown below, if someone could point me in the right direction or show me what it would be really helpfull.
This is what I'd essentially be running on my main method I believe.
**Date date1 = new Date(30, 12, 2013)** // instantiate a new object with those paramaters
**date1.showDate();** // display the original date
**date1.tomorrow();** // shows what that date would be 1 day infront
The problem is right now it's not displaying anything. I thought that by saying dayTomorrow = this.day++; I was adding it's default value + 1 day to the variable dayTomorrow.
public class Date
{
private int day;
private int month;
private int year;
private int dayTomorrow;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public String tomorrow()
{
dayTomorrow = this.day++;
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
return getTomorrow();
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
You just need to use ++this.day, ++this.month and ++this.year. When you use this.day++ it returns the previous date value, not the new. Putting the ++ in the front solves the problem. Also, it changes the day value... you might want to change that to this.day + 1.
Are You calling showDate() after date1.tomorrow() to show your output?
or instead of date1.tomorrow(); call date1.showTomorrow();
Have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
post incremention ...
You could use the native date support in java but I figured you are just practicing right?
This should do the trick:
public class Date {
private int day = 1;
private int month = 1;
private int year = 1970;
private int dayTomorrow = day+1;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
tomorrow();
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
tomorrow();
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public void tomorrow()
{
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
Look carefully for any changes i've made ;)
Here's the main:
public static void main(String[] args) {
Date d = new Date();
d.showDate();
d.showTomorrow();
}

Java code written but no expected output after running

This is a programming assignment I am working on. It takes a single string input that represents a sequence of transactions and prints total gain/loss in the end.
I have my code written and think it should do what I want...but doesn't. I don't get any kind of output after running the program with the specified input.
The input I'm using is:
buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200
share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at
$25 each;sell 200 share(s) at $35 each;
import java.util.*;
import java.text.*;
public class Stocks {
private int shares;
private int price;
private int temp;
private static int total;
private int finalPrice;
private int finalShares;
private Queue<Stocks> StockList = new LinkedList<Stocks>();
private static NumberFormat nf = NumberFormat.getCurrencyInstance();
public Stocks()
{
shares = 0;
price = 0;
}
public Stocks(int shares, int price)
{
this.shares = shares;
this.price = price;
}
public int getShares()
{
return this.shares;
}
public int getPrice()
{
return this.price;
}
public void setShares(int shares)
{
this.shares = shares;
}
public void setPrice(int price)
{
this.price = price;
}
public void sell() {
int sharesToSell = this.getShares();
int priceToSell = this.getPrice();
while (!StockList.isEmpty()) {
int numShares = StockList.peek().getShares();
int sharePrice = StockList.peek().getPrice();
if (numShares < sharesToSell || numShares == sharesToSell) {
temp = sharesToSell - numShares; // remaining shares to sell
finalShares = sharesToSell - temp; // # shares selling at price
finalPrice = priceToSell - sharePrice; // shares sold at adjusted price
total += (finalPrice * finalShares); // Calculates total price
StockList.remove();
sharesToSell = temp; // Remaining shares needed to be sold # price
}
if (numShares > sharesToSell) {
temp = numShares - sharesToSell; // Remaining shares that were bought
finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
total += (finalPrice * sharesToSell); // adds to running total
StockList.peek().setShares(temp);
}
}
}
public void buy() {
int numShares = this.getShares();
int priceToBuy = this.getPrice();
Stocks newStock = new Stocks(numShares,priceToBuy);
StockList.add(newStock); // adds stock to list
int temptotal = (numShares * priceToBuy); // decreases running total
total += (-1 * temptotal);
}
public static int getTotal() { // gets total profit (or loss)
return total;
}
// *****MAIN METHOD*****
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter transaction sequence:");
String input = scan.nextLine().trim();
String[] inputArray = new String[50];
String[] inputArray2 = new String[50];
int numShares, sharePrice;
inputArray = input.split(";");
for (String i : inputArray) {
if (i.toUpperCase().contains("BUY")) {
inputArray2 = i.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.buy();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
}
else if (i.toUpperCase().contains("SELL")) {
inputArray2 = input.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.sell();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
} else {
System.out.println("Error - input does not contain buy/sell");
}
} System.out.println(nf.format(getTotal()));
}
}
You can clean up your parsing a lot by taking a look at java.util.regex.Matcher and java.util.regex.Pattern. They will let you match input against regular expressions. In addition, you can place parens in the regex to extract certain parts. So in your example, you really only care about three things: the operation(buy or sell), the quantity, and the price.
Here's a small example
String sentence = "john programs 10 times a day";
// here's our regex - each set of parens is a "group"
Pattern pattern = Pattern.compile("([A-Za-z]+) programs ([0-9]+) times a day");
Matcher matcher = pattern.matcher(sentence);
String person = matcher.group(1); // here we get the first group
String number = Integers.parseInt(matcher.group(2)); // here we get the second group
System.out.println("Person: " + person + " Number: " + number);
Looks like the main method is returning immediately when it parses a BUY transaction. You probably intended to put the return statement inside the catch block.

Categories