Main Class;
package finalapp;
import java.util.Scanner;
/**
*
* #author bassammetwally
*/
public class FinalApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
Team tem = new Team();
Tournament tour = new Tournament();
System.out.print("Whats the tournament name?\n");
tour.setTourName(input.next());
System.out.print("Please enter the tournamen date\n");
tour.setTourDate(input.next());
System.out.print("Please enter the location\n");
tour.setLocation(input.next());
System.out.print("Please enter number of Software Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of Hardware Stations\n");
tour.setAvaliableHardwareIns(input.nextInt());
System.out.print("Please enter number of field testing");
tour.setAvaliableFieldTesting(input.nextInt());
System.out.print("Please enter max number of teams\n");
tour.setMaxNumberOfTeams(input.nextInt());
tour.tourStatSet(1);
while (true)
{
int choice;
choice = input.nextInt();
if (choice == 1)
{
System.out.printf("Enter Team %s Names\n",tour.getMaxNumberOfTeams());
for (int i = 0; i >= tour.getMaxNumberOfTeams();i++)
{
System.out.print("Please Enter Team Name");
tour.addingTeam(input.next());
tem.teamStats(1);
tem.teamJudgeStat(1);
Have a PREPARING team turn the robot on
(set the robot status to READY) to prepare for inspections
}
}
else if ( choice == 2)
{
System.out.print("Sending prepareing teams");
//for (int a = 0; a >= tour.getTeamsChecked(); a++)
{
}
}
}
}
Question:
I'm making a robot contest simulation, and I'm trying to get the main class to:
Add teams, which I already did
Change status of each team in the array
But my main idea was to go through the ArrayList and change the variables in the other classes, but I couldn't figure out how to do it.
Is there any easier way to do this?
From what it sounds like you should be able to use simple getters and setters to do what you want.
Simply have a method that sets the value you want into an array, and another that gets the array or a specific index in the array. This way you can set and share the array between classes.
Related
Before someone says 'We're not solving your homework, ask your teacher' I only get programming on a Wednesday and this is not homework. It's an extra task that i asked for
Anyways i'm trying to create a program that i can Input a game's name and price then display the titles of all the games(which are in an array) and then another option to display the total price of all games
The issue i'm having is that i can't add to the array(Hard to explain so here's my code )
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static void main(String[] args) {
Java.mainMenu();
}
public static void mainMenu() {
// ArrayList titleArray
// PrimitiveArray priceArray
int choice = 0;
String again = "";
String[] gameTitle = new String[0];
Scanner user_input = new Scanner(System.in);
System.out.println(" Main Menu");
System.out.println("");
System.out.println("1) Enter Game Details");
System.out.println("2) Display Titles in Order");
System.out.println("3) Display Total Price");
System.out.println("");
System.out.println("Choice : ");
choice = user_input.nextInt();
if (choice ==1){
gameDetails(gameTitle);
} else if (choice ==2) {
displayTitles(gameTitle);
} else if (choice ==3) {
}
}
public static void displayTitles(String[] gameTitle) {
// Choice 2
System.out.println(Arrays.toString(gameTitle));
}
public static void gameDetails(String[] gameTitle) {
//Choice 1
String addGameTitle;
double addGamePrice;
Scanner user_input = new Scanner(System.in);
System.out.println("Enter the game Title : ");
addGameTitle = user_input.next();
Java.mainMenu();
}
}
So i run this and put 1 in, it asks me for the Title of the game i enter it but it doesn't get added to the array? Is it because of the way that i am Passing the array?
try doing an array list!
List<array length> <name> = new ArrayList<array length>
<arrayname>.add(<location in array>) = <something>
<arrayname>.add(<location in array>) = <something>
Unfortunately, you will need to have a set length of the array beforehand, which means you can't add to it after you have filled the capacity of the array.
hope this helps!
(Note: I'm relatively new to java myself so I could be forgetting something, or misremembering.)
Thanks to some online assistance from the wonderful stackoverflow users, here is the edits to the enroll and drop student methods to add to the Student array set up. Now it's just on to get the other methods to work as well. Any insight for those would be helpful, especially for speed and efficiency at those points.
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[] { null };// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school Also with Enroll student, should be able to
* assign a class to the student, i.e. Calculas, history, etc
*/
public void enrollStudent(Student newStudent) {
Student newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
public void dropStudent(Student dropStudent) {
Student newStudents[] = new Student[theStudents.length-1];
for (int i = 0; i > theStudents.length; i--)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = dropStudent;
}
// add Test Score for a student
public double addTestScore(String newStudent, double testScore) {
testScores[posi] = testScore;
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
}
// get average average score of a given class
public double averageAverageScore(String course) {
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public String addProgrammingLanguage(String studentName, String programLanguage) {
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select " + "Option 1 to enroll a regular student, \n "
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to
* make it easier to enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newRegularStudent = (String) input.next();
course = input.next();
}
else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make
* it easier to enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array
* to make it easier to enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you want to know the # of students for.");
course = input.next();
Student classSize;
classSize.countClassSize(course);
}
else if (optionNum2 == 2) {
System.out.println("Enter the course name that you want \n"
+ "to calculate the average average test value for.");
course = input.next();
Student testAvg;
testAvg.averageAverageScore(course);
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a \n"
+ "particular programming language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
I don't know if this is the best way, but if I were you, I would just create a new array one size larger or smaller and fill it will the values from the old array each time you add or remove a value. For example:
public void enrollStudent(Student newStudent) {
Students newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
Not very efficient but hey, it doesn't sound like you're doing anything that needs to be super efficient.
This program is meant to prompt a user for address information. Identify the address that would come first by zip code, and then print that address.
I'm having a couple of issues. When I try to assign an int value to the apartment variable, I get an error. Same thing with the zip code portion. Once the minimum value is found, then I want to get the index of the minimum value so that I can print the same index value of each arraylist.
Can someone point me in the right direction or give me a good reference for this? I think I'm just confusing a few things.
package newchapter7;
import java.util.*;
/**
*
* #author Crazy
*/
public class Address {
ArrayList<Integer> houses = new ArrayList<>();
ArrayList<String> streets = new ArrayList<>();
ArrayList<Integer> apts = new ArrayList<>();
ArrayList<String> cities = new ArrayList<>();
ArrayList<String> states = new ArrayList<>();
ArrayList<Integer> zips = new ArrayList<>();
int minValue;
/**
* Adds a house number to the address
* #param house house number
*/
public void addHouse(int house)
{
houses.add(house);
}
public ArrayList<Integer> getHouse()
{
return houses;
}
/**
* Adds a street name to the address
* #param street street name
*/
public void addStreet(String street)
{
streets.add(street);
}
public ArrayList<String> getStreet()
{
return streets;
}
/**
* constructor to add an apartment number that equals 0
*/
public void addApt()
{
}
/**
* Adds an apartment number to the address
* #param aptNbr apartment number
*/
public void addApt(int aptNbr)
{
apts.add(aptNbr);
}
public ArrayList<Integer> getAptNbrs()
{
return apts;
}
/**
* Adds a city to the address
* #param city city
*/
public void addCity(String city)
{
cities.add(city);
}
public ArrayList<String> getCity()
{
return cities;
}
/**
* Adds a state to the address
* #param state state
*/
public void addState(String state)
{
states.add(state);
}
public ArrayList<String> getState()
{
return states;
}
/**
* Adds a zip code to the address
* #param zip zip code
*/
public void addZip(int zip)
{
zips.add(zip);
}
public ArrayList<Integer> getZip()
{
return zips;
}
public int arrValue()
{
minValue = zips.indexOf(Collections.min(zips));
return minValue;
}
}
Main
package newchapter7;
import java.util.*;
public class NewChapter7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Address addy = new Address();
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
String street1 = in.next();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}
}
}
This is a homework assignment. I think I've confused the material quite a bit and even if this works, I would like to learn a more efficient way to accomplish the same task.
Error
Please enter a house number: 772
Please enter the street name: Apple Drive
Exception in thread "main" java.util.InputMismatchException
Please enter an apartment number if applicable:
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at newchapter7.NewChapter7.main(NewChapter7.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 21 seconds)
Assignment:
Implement a class Address. An address has a house number, a street, an optional apartment number, a city, a state, and a postal code. Supply two constructors: one with an apartment number and one without. Supply a print method that prints the address with the street on one line and the city, state, and postal code on the next line. Supply a method public boolean comesBefore (Address other) that tests whether this address comes before another when the addresses are compared by postal code.
Your Address class is mixed up and actually seems backwards to me. I think that you'd be much better off if it represented the state of a single address. If so, then it should not hold ArrayLists, but rather individual fields for a single house with getter and setter methods for each field, a constructor that accepts the field parameters, and perhaps a default constructor that accepts no parameters if desired.
Then if you need to work with many Addresses, you can create a single ArrayList<Address> for this.
Note that as an aside, I wouldn't use int for apartment number or zip code. While these look like numbers and comprise the digits of numbers, they don't behave as numbers. Use String instead.
change
String street1 = in.next();
addy.streets.add(street1);
line to
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
and other next() to nextLine() also.
Ok the suggestion above is not working this is the full working code, but you have a possible logical error in this. Since it is homework you should be able to solve that. However...
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
in.nextLine();
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}
I am really struggling with get/set methods. I understand the basic concept - first you set the value then you retrieve it. I am finding it rather difficult to find information about it with the minimal concepts I have already learned. I am on the 6th chapter or my first Java and programming class and it is all online. I created a couple other classes that used set/get methods, but those don't really seem to fit this project.
public class Purchase{
int inv;
double sale;
double tax;
double taxAmount = 0.05;
public int getInv()
{
return inv;
}
public void setInv(int inv)
{
inv = inv;
}
public void setSale(double s)
{
sale = s;
tax = sale * taxAmount;
}
public double getSale()
{
return sale;
}
//display
public void display()
{
System.out.println("Invoice number: " + getInv() + "\nSale amount: $" + getSale() + "\nTax: $" + tax + "\nTotal: $" + (tax + sale));
}
}
import java.util.Scanner;
public class CreatePurchase{
public static void main(String[] args)
{
Purchase one = new Purchase();
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
}
while(inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
sale = input.nextInt();
}
}
}
The CreatePurchase class is not finished, but I compile it and get the below for every variable every time it appears:
CreatePurchase.java:16: error: cannot find symbol
inv = input.nextInt();
^
It was my understanding that a default constructor is made, so I didn't add one, but called it in CreatePurchase.
Any suggestions?
You've failed to declare the variable inv any where, for example...
public static void main(String[] args) {
Purchase one = new Purchase();
// !! Variable must be declared before it can be used !! //
int inv = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
one.setInv(inv);
} while (inv < 1000 && inv > 8000);
{
System.out.println("Please enter the amount of your sale. ");
// This will be your next problem...
sale = input.nextInt();
}
}
Your Purchase class is also going to have problems...
The following method is essentially assigning the value of inv back to itself, which is meaningless in this context...
public void setInv(int inv)
{
inv = inv;
}
Instead, you should be assigning to the instance of the Purchase class's inv variable...
public void setInv(int inv)
{
this.inv = inv;
}
You have at least two problems. First, you can create a new variable with the same name as another variable that's in a bigger container (scope). In this case, the new variable "hides" or "shadows" the outer one. In your setInv method, when you say inv = inv, both invs refer to the innermost variable, the one in the method signature. To save the argument to the class's field, you need to specify the outer inv: this.inv = inv;.
In your CreatePurchase class, you don't have any inv defined; there's one in Purchase, but that's over there, not here. You just need to declare int inv; right after your Purchase one.
Based on these two errors, I would recommend reading an article or tutorial about variable scope in Java to learn the rules about which variables are accessible where.
You havent declared the variable inv in main method, at this step
inv = input.nextInt();
Change your program to below
int inv = 0;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please enter you invoice number. This will be a number between 1000 and 8000. ");
inv = input.nextInt();
if(inv >1000 & inv <8000)
one.setInv(inv);//add to one variable only if its correct,otherwise ignore it
}
while(inv < 1000 && inv > 8000);
Here's the code I have so far. This is the error I get for line 58
incompatible types required: ArrayList found:
VendProduct
(Alt-Enter shows hints)
//A vending machine to dispense multiple products
package newvendingmachine;
import java.util.ArrayList;
import java.util.Scanner;
//Tony Moore
public class NewVendingMachine{
//Set class data
static String[] product = {"Chips", "M&Ms", "Peanuts", "Popcorn", "Snickers"};
static Float[] cost = {.50f, .75f, .75f, .75f, .90f};
static Integer[] inventory = {20, 20, 20, 20, 20};
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<VendProduct> vp = new ArrayList<>();
for (int idx=0; idx<product.length; idx++) {
vp.add(new VendProduct());
}
//Accept user input
Scanner input = new Scanner(System.in);
int userInput;
while (true) {
// Display menu graphics
System.out.println(" Options: Press your selection then press enter ");
System.out.println(" 1. "+product[0]+" ");
System.out.println(" 2. "+product[1]+" ");
System.out.println(" 3. "+product[2]+" ");
System.out.println(" 4. "+product[3]+" ");
System.out.println(" 5. "+product[4]+" ");
System.out.println(" 6. Quit ");
userInput = input.nextInt();
if (userInput <1 || userInput >6) {
System.out.println("Please make a vaild selection");
}
if (userInput >=1 || userInput <=6) {
vp = (VendProduct)vp.get(userInput-1);
vp.buyProduct();
}
if (userInput == 6) {
System.out.println("Thanks, and come back soon");
break;
}
}
}
}
vp = (VendProduct)vp.get(userInput-1);
vp is an ArrayList of VendProduct, but you're trying to set it to just one VendProduct...
You should create a variable of the type VendProduct and use that, like this:
VendProduct product = vp.get(userInput-1);
product.buyProduct();
You could also do vp.get(userInput-1).buyProduct(); directly in one line. That's up to you. Using two lines usually makes the code a bit cleaner and easier to read.