Need help using an ArrayList - java

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

Related

Error in Java Method Cant get it to print to the console

I'm not sure where I went wrong but I could use some help. I'm new to JAVA and I'm not sure where I'm going wrong. Just trying to get the items in the public void method to print to my console.
public class HomersDonutShop {
public static void main (String[] args) {
//Creates flavor array
String[] donutFlavors = new String[4];
donutFlavors[0]= "Chocolate";
donutFlavors[1]= "Vanilla";
donutFlavors[2]= "Chocolate With Sprinkles";
donutFlavors[3]= "Blueberry";
//default is chocolate. prints string with array selected
System.out.println("You picked " +donutFlavors[0]+"."+" Great choice!!");
//creates donut rating
final int donutRating[] = new int[5];
donutRating[0] = 1;
donutRating[1] = 2;
donutRating[2] = 3;
donutRating[3] = 4;
donutRating[4] = 5;
//default is 5 prints string with array selected
System.out.println("You gave " +donutFlavors[0]+" donuts"+" a rating of"+ " "+donutRating[4]);
}
public void makeDonuts(){
donutCount = donuCount + 1;
System.out.println("Time to mke more donuts."+" MMMMMMMM DOOOONNNUUUUTSSS.");
}
public void buyMoreIngredients() {
int ingredients = 10;
while (ingredients >= 10)
System.out.println(ingredients);
ingredients--;
if (ingredients <=1) {
System.out.println("Time to go shopping");
}
}
}

Array not printing out correctly

I've tried moving around my curly braces and just the entire structure of this program a bunch and can't seem to point out how to make this print out correctly. I have a text file that looks like this:
Game of Thrones|Action|HBO|50|Favorite
House of Cards|Drama|Netflix|50|Favorite
Huckabee|Bad Show|Fox News|25|Not favorite
Survivor|Reality|NBC|45|Not favorite
The Daily Show with Jon Stewart|Comedy|Comedy Central|30|Favorite
Louie|Comedy|FX|30|Favorite
Sports Center|Sports News|ESPN|60|Favorite
The Big Bang Theory|Comedy|CBS|30|Not favorite
Sesame Street|Educational|PBS|30|Favorite
Chopped|Food Show|Food Network|60|Favorite
I want my console to show this (minus the pipes) with a toString() that I have, which works perfectly fine, but it prints out with 10 copies of each show and I'm not sure what I can go about doing differently to fix this.
Question: How can I make it so the console prints out exactly 1 copy of each show instead of 10?
Driver Code:
public class TVShowDriver {
public static void main(String[] args) throws FileNotFoundException {
TVShow[] tvShow = new TVShow[10];
String tvName = "";
String genre = "";
String network = "";
int runningTime = 0;
String favorite = "";
// reads in Shows.txt
File tvShows = new File("./src/Shows.txt");
Scanner fileScanner = new Scanner(tvShows);
// while there is a new line in the data, goes to the next one
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\\|");
// while there is a new attribute to read in on a given line, reads
// data
while (lineScanner.hasNext()) {
tvName = lineScanner.next();
genre = lineScanner.next();
network = lineScanner.next();
runningTime = lineScanner.nextInt();
favorite = lineScanner.next();
// creates a show
for (int i = 0; i < tvShow.length; i++) {
tvShow[i] = new TVShow(tvName, genre, network, runningTime,
favorite);
}
}
// prints out shows
for (int i = 0; i < 10; i++) {
System.out.println(tvShow[i]);
}
}
}
}
TVShow Class:
public class TVShow {
private String tvName;
private String genre;
private String network;
private int runningTime;
private String favorite;
public TVShow(String tvName, String genre, String network, int runningTime, String favorite)
{
this.tvName = tvName;
this.genre = genre;
this.network = network;
this.runningTime = runningTime;
this.favorite = favorite;
}
public String getTvName() {
return tvName;
}
public void setTvName(String tvName) {
this.tvName = tvName;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
public int getRunningTime() {
return runningTime;
}
public void setRunningTime(int runningTime) {
this.runningTime = runningTime;
}
public String getFavorite() {
return favorite;
}
public void setFavorite(String favorite) {
this.favorite = favorite;
}
public String toString()
{
return "TV Show Name: " + tvName + ", Genre: " + genre + ", Network: " + network + ", Running Time: " + runningTime + " mins" + ", Favorite: " + favorite;
}
}
This...
// creates a show
for (int i = 0; i < tvShow.length; i++) {
tvShow[i] = new TVShow(tvName, genre, network, runningTime,
favorite);
}
...is wrong. Basically, each time you read a line from the file, you are re-filling the array with that show's details (sure you're making a new instance of TVShow, but it contains all the same details.
Instead, use a separate iteration value and increment each time you read a new line...
int currentLine = 0;
while (lineScanner.hasNext()) {
if (currentLine < tvShow.length) {
tvName = lineScanner.next();
genre = lineScanner.next();
network = lineScanner.next();
runningTime = lineScanner.nextInt();
favorite = lineScanner.next();
tvShow[currentLine] = new TVShow(tvName, genre, network, runningTime,
favorite);
currentLine++;
} else {
System.err.println("The array is full");
break;
}
}
I think your problem lies in this piece:
// creates a show
for (int i = 0; i < tvShow.length; i++) {
tvShow[i] = new TVShow(tvName, genre, network, runningTime,favorite);
}
You seem to be filling up the tvShow array each time with ten (which is the length of the array) copies of the same show.
A solution is to have a counter outside of your first while loop which you increment. Then use that counter to index into tvShow.
Alternatively, if you just want to print each show you could not bother to save them all in an array, create a TVShow variable outside of the while loops and reassign it.
So that would look like:
TVShow myShow; // outside of the first while loop loop
myShow = new TVShow(tvName, genre, network, runningTime,favorite); // where you were assigning into the array

Displaying Pictures in Array

In drjava I'm trying to acquire pictures in hold them in the array, and then print out a description of each picture. Right now everything compiles but when I run it has me choose the folder that contains the pictures and then the interactions pane disappears. The code I have so far is in my House app for acquiring the pictures and printing the descriptions is
SSCCEE
HOUSE.java
public class House
{
String owner;
public final static int CAPACITY = 6;
Picture[ ] pictArray = new Picture[CAPACITY];
public House(String pString)
{
this.owner = pString;
}
public String toString()
{
return("The House owned by " + this.owner);
}
public void acquire( int position, Picture pRef )
{
this.pictArray[ position ] = pRef;
}
public void printPictures()
{
for (int i=0; i < this.pictArray.length;i++)
{
System.out.print("The Picture in position " + i + " is ");
System.out.println( this.pictArray[ i ]);
}
}
public void swap( int positionA, int positionB )
{
System.out.println("NOTHING DONE. THIS IS JUST A swap's STUB");
}
public void showOff()
{
System.out.println("NOTHING DONE. THIS IS JUST showOff's STUB");
}
}
Test.java
import java.util.Scanner;
public class Test
{
public static void main(String[] a)
{
House h = new House("Justin Chaisetseree");
Scanner sc = new Scanner(System.in);
FileChooser.pickMediaPath();
for( int i = 0; i < 6; i++)
{
h.acquire(i,new Picture(FileChooser.pickAFile()));
}
h.printPictures();
h.showOff();
Boolean done = false;
while( ! done )
{
System.out.println("Which two do you want to swap?");
System.out.print("Type in two numbers from 0 to ");
System.out.print( 5 );
System.out.println(" or two -1s to stop.");
int userInput1 = sc.nextInt();
int userInput2 = sc.nextInt();
if( userInput1 < 0 || userInput2 < 0)
{
done = true;
}
else
{
h.swap( userInput1, userInput2 );
}
}
h.showOff();
}
}

Finding smallest and largest population and the average

I've been working on getting this program to work. I'm having a little trouble getting the program to read the files I have created, census2000 and census2010. These contain the 50 states and their population in 2000 and 2010. I believe that the rest of my program is correct. I was told to use methods to find the smallest population, largest population and the average. Here is two lines from the 2000 file:
Alabama 4447100
Alaska 626932
Here is my program:
public static void main(String[] args) throws IOException {
String state = "";
int population = 0;
int p = 0, s = 0, pop = 0, stat = 0, populate = 0, sum = 0;
File f = new File("census2000.txt");
Scanner infile = new Scanner(f);
infile.useDelimiter("[\t|,|\n|\r]+");
while (infile.hasNext()) {
checksmall(p, s);
checklargest(pop, stat);
checkAverage(populate, sum);
population = infile.nextInt();
state = infile.next("/t");
System.out.println(state + "has" + population + "people");
}
System.out.println(state + "has smallest population of" + population);
prw.close();
}
public static boolean checksmall(int p, int s) {
boolean returnValue;
if (p < s) {
returnValue = true;
} else {
returnValue = false;
}
return (returnValue);
}
public static boolean checklargest(int pop, int stat) {
boolean returnVal;
if (pop > stat) {
returnVal = true;
} else {
returnVal = false;
}
return (returnVal);
}
public static int checkAverage(int populate, int sum) {
int retVal;
retVal = populate + sum;
return (retVal);
}
}
What am I doing wrong?
I believe the problem is here:
state = infile.next("/t");
I think what you're trying to do is skip a tab in the file and read the state? You could do that by reading in the line and then splitting the line using \t as the delimiter.
String line;
while (infile.hasNextLine()){
line = infile.nextLine();
String data[] = line.split("\\s+");
state = data[0];
population = Integer.parseInt(data[1]);
}
edit: also as the other answer points out, you're attempting to perform functions on the file's data before it's read.
You need to be calling checksmall, checklargest and checkAverage after/while the file is loaded.

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