So, I'm trying to figure out how to get values of an array list from another class and print certain values depending on user input.
For example, firstly a user is asked to provide a location, once they enter a location, it has to read the user input and output the results according to the location.an image is provided about the output.
For some reason it doesn't output the correct values from array list.
Could you please help me out?
This is my code for reading values from array list.
public class Program {
ArrayList<Properties> property = Properties.getMelbnbProperty();
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
ArrayList<Properties> output = Properties.getMelbnbProperty();
if(Properties.getMelbnbProperty().contains(choice)) {
output.addAll(Properties.getMelbnbProperty());
}
} }
This is my code for array list.
public class Properties {
public static ArrayList<Properties> getMelbnbProperty() {
// Below is an arraylist where I have stored the Melbnb data
ArrayList<Properties> property = new ArrayList<Properties>();
property.add(new Properties("Private room in the heart of Southbank"));
property.add(new Properties("Spacious bedroom in a cosy apartment in South Yarra\n"));
property.add(new Properties("Ensuite room with great views"));
property.add(new Properties("Single room next to Carlton Gardens"));
property.add(new Properties("Studio close to Melbourne CBD"));
property.add(new Properties("1-bedroom CBD view suite near Melbourne Central and RMIT"));
property.add(new Properties("Stylish two bedroom in CBD"));
property.add(new Properties("Sky high studio with amazing views"));
property.add(new Properties("Budget accommodation bunk beds"));
property.add(new Properties("A beautiful room near Marvel Stadium"));
return property;
}}
The code you have provided in your question post is incomplete and in a way doesn't make sense to what your image displays. I do however understand what you are trying to accomplish but the way I see it your properties class is somewhat under-nourished.
I don't know if this is the intentional purpose but your for loop:
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
is designed to pull out 1 object from the property ArrayList. This loop is completely unnecessary since just supplying an index value of 1 to the ArrayList#get() method does exactly the same thing and is only a single line of code, for example:
System.out.println(property.get(1));
I say this because your for loop initializer starts at index 1, there is no iterator for the loop, and you apply the break statement directly after the display of the object within the ArrayList.
To access all elements within the ArrayList (your post indicates) you would need to do something like this:
for (int i = 0; i < properties.size(); i++) {
System.out.println(properties.get(i));
}
Or you can use:
for (String props: properties) {
System.out.println(props);
}
To be honest, what you are showing for code in grossly underdeveloped. I don't want to come across as insulting but it's obvious that you are not showing as much as you should be and therefore it is extremely difficult to provide you with any concrete solution to your problem. For this reason, I think it is just easier to provide you with a working demo console application which would allow you to perhaps grasp some concepts from.
The runnable code below consists of two specific classes, the start up class named SimpleBNBDemo which contains the main() method and the Properties class which allows you to instantiate instances of different BNB properties. As you can see, the Properties class is somewhat more fulfilled than the class you provided in your question post. Take the time to read through the code and try to follow its flow. Do keep in mind, although runnable this is only a Demo application and is in now way a complete works. I personally would never hard-code fill an ArrayList with Object data. This data should come from and or saved to a file system or database. However, for demo purposes this will suffice.
The SimpleBNBDemo class:
public class SimpleBNBDemo {
// Field variables
public final static String LS = System.lineSeparator();
public final static java.util.Scanner USER_INPUT = new java.util.Scanner(System.in);
// class member variable
private Properties prop = new Properties();
private final String line = "------------------------------------------------";
private int pwAttempts = 0;
public static void main(String[] args) {
// Started this way to avoid the need for statics
new SimpleBNBDemo().startApp(args);
}
private void startApp(String[] args) {
/* Create Properties instances...
You can do this with whatever means you like. */
java.util.List<Properties> properties = prop.getProperties();
properties.add(new Properties("Southbank Mannor", "Room", "Private room in the heart of Southbank.", "South", 86.00d, true));
properties.add(new Properties("Yarra House", "Room", "Spacious bedroom in a cosy apartment in South Yarra.", "South", 74.00d, true));
properties.add(new Properties("Ensuite Haven", "Room", "Ensuite room with great views.", "West", 65.50d, true));
properties.add(new Properties("Carlton Place", "Room", "Single room next to Carlton Gardens.", "South", 78.00d, true));
properties.add(new Properties("Melbourne Studio", "Studio", "Studio close to Melbourne CBD.", "East", 78.00d, true));
properties.add(new Properties("Melbourne Delight", "Room", "1-bedroom CBD view suite near Melbourne Central and RMIT.", "North", 135.00d, true));
properties.add(new Properties("CBD House", "Suit", "Stylish two bedroom in CBD.", "West", 100.00d, true));
properties.add(new Properties("Sky-High", "Studio", "Sky high studio with amazing views.", "North", 95.00d, true));
properties.add(new Properties("Budgeteer", "Room", "Budget accommodation bunk beds.", "South", 65.00d, true));
properties.add(new Properties("Stadium House", "Room", "A beautiful room near Marvel Stadium.", "East", 95.00d, true));
println("Welcome to MelBNB" + LS + line);
println();
// Menu 1 - Main Menu
String choice = "";
String[] locations = prop.getAllLocations();
if (locations.length == 0) {
printErr("No BNB's with Location in database yet!");
return;
}
while (choice.isEmpty()) {
println("Select from Main Menu:");
println(" 1) List all Accomodations");
println(" 2) Search by location");
println(" 3) Browse by type of accomodation");
println(" 4) Filter by rating");
println(" 5) Rate an accomodation");
println(" 6) Exit (quit)");
print("Please choose: -> ");
choice = USER_INPUT.nextLine().trim();
// Validate Entry...switch/case works great for input validation.
switch (choice) {
case "1":
listAllAccomodations();
break;
case "2":
searchByLocation();
break;
case "3":
searchByAccomodationType();
break;
case "4":
searchByRating();
break;
case "5":
rateAnAccomodation();
break;
case "6":
break;
case "~admin~":
adminMenu();
break;
case "~admin attempts reset~":
pwAttempts = 0;
println();
break;
default:
println("Invalid Entry (" + choice + ")! Try again..." + LS);
}
// Was 'Exit' (4) selected?
if (choice.equals("6")) {
// Break out of loop to end application.
println(LS + "Thank you for visiting MelBNB, Bye-Bye." + LS);
break;
}
choice = ""; // Reset 'choice' to be empty in order to loop again..
}
}
private void adminMenu() {
String pwrd = "";
while (pwrd.isEmpty()) {
if (pwAttempts >= 3) {
println(LS + "Admin Menu is NOT Available!" + LS + "To many failed "
+ "consecutive password attempts!" + LS + "Only " + pwAttempts
+ " consecutive attempts are allowed." + LS);
return;
}
print(LS + "Please enter Admin Password (c to cancel): --> ");
pwrd = USER_INPUT.nextLine().trim();
if (pwrd.equalsIgnoreCase("c")) {
println();
return;
}
int psum = 0;
for (int i = 0; i < pwrd.length(); i++) {
psum += pwrd.charAt(i);
}
if (psum != 624) {
pwAttempts++;
println("Invalid Password! Try again...");
pwrd = "";
}
}
pwAttempts = 0;
println();
println("***********************************************");
println("*** Administrative options would go here! ***");
println("*** Press Enter To Continue ***");
println("***********************************************");
String nothing = USER_INPUT.nextLine().trim();
}
private void listAllAccomodations() {
println(LS + "All Available Accomodations:");
println("----------------------------");
int cntr = 0;
String underline = "";
for (Properties pp : prop.getProperties()) {
cntr++;
String str = pp.toStringTable(pp, cntr == 1);
underline = String.join("", java.util.Collections.nCopies(str.length(), "="));
println(str);
if (cntr == 15) {
println("<- Press Enter To Continue ->");
String nuthin = USER_INPUT.nextLine().trim();
cntr = 0;
}
}
println(underline + LS);
}
private void searchByLocation() {
String[] locationTypes = prop.getAllLocations();
java.util.Arrays.sort(locationTypes);
String locationChoice = "";
while (locationChoice.isEmpty()) {
println();
println("Select the desired location:");
int i = 0;
for ( ; i < locationTypes.length; i++) {
println(" " + (i + 1) + ") " + locationTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
locationChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!locationChoice.matches("[1-" + (locationTypes.length + 1) + "]")) {
println("Invalid Entry (" + locationChoice + ")! Try again..." + LS);
locationChoice = "";
}
}
if (locationChoice.equals(String.valueOf(locationTypes.length + 1))) {
println();
return;
}
String location = locationTypes[Integer.valueOf(locationChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByLocation(location);
if (p.isEmpty()) {
println("No accomodations available in the " + location + " area!" + LS);
return;
}
String str = "Available accomodation within the " + location + " area:";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByAccomodationType() {
String[] accTypes = prop.getAllAccomodationTypes();
java.util.Arrays.sort(accTypes);
String accChoice = "";
while (accChoice.isEmpty()) {
println();
println("Select the desired accomodation type:");
int i = 0;
for ( ; i < accTypes.length; i++) {
println(" " + (i + 1) + ") " + accTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
accChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!accChoice.matches("[1-" + (accTypes.length + 1) + "]")) {
println("Invalid Entry (" + accChoice + ")! Try again..." + LS);
accChoice = "";
}
}
if (accChoice.equals(String.valueOf(accTypes.length + 1))) {
println();
return;
}
String acc = accTypes[Integer.valueOf(accChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByAccomodationType(acc);
if (p.isEmpty()) {
println("No accomodation type of " + acc + " is available!" + LS);
return;
}
String str = "Available accomodation that are of type '" + acc + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByRating() {
String rateChoice = "";
while (rateChoice.isEmpty()) {
println();
println("Enter the desired accomodation rating (1 to 5);");
print( "Enter c to cancel. Desired Rating: --> ");
rateChoice = USER_INPUT.nextLine().trim();
if (rateChoice.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateChoice.matches("[1-5]")) {
println("Invalid Entry (" + rateChoice + ")! Try again..." + LS);
rateChoice = "";
}
}
int rating = Integer.valueOf(rateChoice);
java.util.List<Properties> p = prop.getPropertiesByRating(rating);
if (p.isEmpty()) {
println("No accomodation available with the rating of " + rating + "!" + LS);
return;
}
String str = "Available accomodation with a rating of '" + rating + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void rateAnAccomodation() {
/* Displayed ratings are always the AVERAGE of all ratings
provided for that particular propety. This is done within
the 'Properties.addRating()' method. For this reason and
for other obvious reasons the Properties List should be
saved to either a file or a database. If this is not done
then all added or modified data will be lost when the
application closes. The Properties List data should NOT
be hard-coded. It should be loaded in when the application
starts and saved to storage when data is added or modified.
*/
String[] pNames = prop.getAllPropertyNames();
String nameToRate = "";
while (nameToRate.isEmpty()) {
println(LS + "Enter the name of the accomodation you want to rate:");
print( "Enter 'c' to cancel. Rating: --> ");
nameToRate = USER_INPUT.nextLine().trim();
if (nameToRate.equalsIgnoreCase("c")) {
return;
}
// Validate Entry............................
if (nameToRate.isEmpty()) {
println("Invalid Entry! You must enter a Name! Try again...");
nameToRate = "";
continue;
}
// Does the name exist in List?
boolean found = false;
for (String name : pNames) {
if (name.equalsIgnoreCase(nameToRate)) {
// Yes it does...
found = true;
break; // Break out of this loop.
}
}
if (!found) {
println("Invalid Entry (" + nameToRate + ")!" + LS
+ "Can not find the name supplied! Try again..." + LS);
nameToRate = "";
}
}
//.................................................
/* If we get to here then the name supplied
(regarless of letter case) is in the List. */
String rateNum = "";
while (rateNum.isEmpty()) {
println();
print("Enter your rating (1 to 5 or 'c' to cancel): --> ");
rateNum = USER_INPUT.nextLine().trim();
if (rateNum.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateNum.matches("[1-5]")) {
println("Invalid Entry (" + rateNum + ")! Try again..." + LS);
rateNum = "";
}
println();
}
// Set the rating.
int rating = Integer.valueOf(rateNum);
for (Properties p : prop.getProperties()) {
if (p.getPropertyName().equalsIgnoreCase(nameToRate)) {
int avgRating = p.getAverageRating();
p.addRating(rating);
println("Your rating of " + rating + " has been added to the accomodation" + LS
+ "named '" + nameToRate + "' which has moved its overall rating" + LS
+ "average from " + avgRating + " to an overall average rating of " +
p.getAverageRating() + "." + LS + "This is based on " +
p.getTotalNumberOfRatingsDone() + " rating(s) on the accomodation." + LS);
}
}
}
public static void println(Object... obj) {
if (obj.length > 0) {
System.out.println(obj[0]);
}
else {
System.out.println();
}
}
public static void printErr(Object... obj) {
if (obj.length > 0) {
System.err.println(obj[0]);
}
else {
System.err.println();
}
}
public static void print(Object... obj) {
if (obj.length > 0) {
System.out.print(obj[0]);
}
else {
System.out.print("");
}
}
}
The Properties class:
public class Properties {
public static java.util.List<Properties> properties = new java.util.ArrayList<>();
private String propertyName;
private String accomodationType;
private String description;
private String location;
private double pricePerDay;
private int averageRating = 0;
private int totalNumberOfRatings;
private boolean available;
// Constructor #1
public Properties() { }
// Constructor #2
public Properties(String propertyName, String accomodationType, String description,
String location, double pricePerDay, boolean available) {
this.propertyName = propertyName;
this.accomodationType = accomodationType;
this.description = description;
this.location = location;
this.pricePerDay = pricePerDay;
this.available = available;
}
// Getters & Setters
public java.util.List<Properties> getProperties() {
return properties;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getAccomodationType() {
return accomodationType;
}
public void setAccomodationType(String accomodationType) {
this.accomodationType = accomodationType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getPricePerDay() {
return pricePerDay;
}
public void setPricePerDay(double pricePerDay) {
this.pricePerDay = pricePerDay;
}
public int getAverageRating() {
return this.averageRating;
}
public void addRating(int rating) {
// Rateing is an integer value from 1 to 5.
// Where 1 is Bad and 5 Excellent.
if (rating < 1) { rating = 1; }
else if (rating > 5) { rating = 5; }
int sum = 0, r = 0;
for (Properties p : properties) {
if (p.propertyName.equalsIgnoreCase(this.propertyName)) {
r++;
sum += rating;
}
}
if (sum > 0 && r > 0) {
this.averageRating = sum / r;
}
else {
this.averageRating = rating;
}
this.totalNumberOfRatings++;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public String toString() {
return propertyName + ", " + accomodationType + ", " + description + ", "
+ location + ", " + pricePerDay + ", " + averageRating + ", "
+ available;
}
public String toStringTable(Properties p, boolean... addHeader) {
boolean applyHeader = false;
if (addHeader.length > 0) {
applyHeader = addHeader[0];
}
String symbol = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
String header = "", underline = "", ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
header = String.format("%-18s %-10s %-50s %-10s %-10s %-8s %-6s%n", "BNB Name",
"BNB Type", "BNB Description", "Location", "Price/Day", "Rating", "Avail.");
underline = String.join("", java.util.Collections.nCopies(header.length(), "=")) + ls;
if (applyHeader) {
sb.append(header).append(underline);
}
String[] desc = p.description.split("\\s+");
java.util.List<String> descTmp = new java.util.ArrayList<>();
StringBuilder sb2 = new StringBuilder("");
for (String str : desc) {
if ((sb2.toString() + " " + str).length() > 50) {
descTmp.add(sb2.toString());
sb2.setLength(0);
}
if (!sb2.toString().isEmpty()) {
sb2.append(" ");
}
sb2.append(str);
}
if (!sb2.toString().isEmpty()) {
descTmp.add(sb2.toString());
}
sb.append(String.format("%-18s %-10s %-50s %-12s " + symbol + "%-10.2f %-7s %-6s",
p.propertyName, p.accomodationType, descTmp.get(0), p.location,
p.pricePerDay, p.averageRating, (p.available ? "Yes" : "No")));
if (descTmp.size() > 1) {
for (int i = 1; i < descTmp.size(); i++) {
sb.append(ls).append(String.format("%-18s %-10s %-50s %-12s %-10s %-7s %-6s",
" "," ", descTmp.get(i), " ", " ", " ", " "));
}
}
return sb.toString();
}
public String[] getAllPropertyNames() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure names retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.propertyName)) {
tmp.add(prop.propertyName);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllAccomodationTypes() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure accomodations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.accomodationType)) {
tmp.add(prop.accomodationType);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public java.util.List<Properties> getPropertiesByLocation(String location) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.location.equalsIgnoreCase(location) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByAccomodationType(String accomodationType) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.accomodationType.equalsIgnoreCase(accomodationType) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByRating(int rating) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.averageRating == rating && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public int getTotalNumberOfRatingsDone() {
return this.totalNumberOfRatings;
}
public String[] getAllDescriptions() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure descriptions retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.description)) {
tmp.add(prop.description);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllLocations() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.location)) {
tmp.add(prop.location);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public double[] getAllPerDayPrices() {
java.util.List<Double> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.pricePerDay)) {
tmp.add(prop.pricePerDay);
}
}
// Convert List<Double> to double[]...
double[] prices = new double[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
prices[i] = tmp.get(i);
}
return prices;
}
}
Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}
I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
StringTokenizer st = new StringTokenizer(str2,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct1 = new Indicator (cCode,iName,iCode,data);
bigdata.insertAtBack(idct1);
str2 = br2.readLine();
}
//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(bigdata,search3);
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
public static void searchYear (myLinkedList bigdata, int searchTerm) {
Indicator idct4 = (Indicator)bigdata.getFirst();
boolean found = false;
while(idct4 != null){
if(idct4.getDYear() == searchTerm) {
found = true;
System.out.println(idct4.getDValue());
}
idct4 = (Indicator)bigdata.getNext();
}
if (!found){
String message = "Error!";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
}
}
indicator class:
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
public String getCCode(){return cCode;}
public String getIName(){return iName;}
public String getICode(){return iCode;}
public int getDYear(){return d.getYear();}
public String getDValue(){return d.getValue();}
public void setCCode(String cCode){this.cCode = cCode;}
public void setIName(String iName){this.iName = iName;}
public void setICode(String iCode){this.iCode = iCode;}
public String toString(){
return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
}
}
MyData class:
public MyData(int year, String value){
this.year = year;
this.value = value;
}
public int getYear(){return year;}
public String getValue(){return value;}
public void setYear(int year){this.year = year;}
public void setValue(String value){this.value = value;}
public String toString(){
return (value + "(" + year + ")");
}
I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(idct3,search3); // Indicator passed in here
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
for (int i = 0; i < indicator.DataList.size(); i++) {
if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() + " having value " + indicator.DataList.get(i).getValue());
return; // Exit this method
}
}
System.out.println("Not Found");
}
I need to be able to use different methods in order to print out certain table content such as a sum, multiplication, or random table to name a few. I cannot figure out how to print out this content separate from the row ID. another problem I am having is when I enter "f" to reprint the table the header gets repeated each time I print it which just creates a very long repeating header after a few reprints, could someone help with this?
The original code will be followed by the IntTable class, it is not completely filled out which I am aware of but I want to figure this out before I move on.
import java.util.Scanner;
public class Assignment6{
public static String returnMenu(){
String menu = "Command Options---------------\na: Create a new table\nb: Change the row sizes\nc: Change the column sizes\nd: Change the data types\ne: Chnge the formats\nf: Display the table\ng: Display the log data\n:?: Display this menu\nq: Quit the program\n------------------------------";
return menu;
}
public static void main(String[] arg){
Scanner scan = new Scanner(System.in);
String input = "p";
String output = "NOOOOO!";
IntTable myTable = new IntTable();
while (!input.equals("q")){
System.out.println("Please input a command: ");
input = scan.nextLine();
if (input.equals("a")){
System.out.print("a [Input three integers to initialize table]: ");
myTable.setRow(scan.nextInt()); myTable.setColumn(scan.nextInt()); myTable.setType(scan.nextInt());
scan.nextLine();
myTable.printTable();
}
else if (input.equals("b")){
System.out.print("b [Enter integer to update table row]: ");
myTable.setRow(scan.nextInt());
scan.nextLine();
}
else if (input.equals("c")){
System.out.println("c [Enter integer to update column]: ");
myTable.setColumn(scan.nextInt());
scan.nextLine();
}
else if (input.equals("d")){
System.out.println("d [Enter integer to update data type]: ");
myTable.setType(scan.nextInt());
scan.nextLine();
}
else if (input.equals("e")){
System.out.println("e [Enter integer to update printf format]: ");
}
else if (input.equals("f")){
System.out.println("f [Display table]: ");
myTable.printTable();
}
else if (input.equals("g")){
System.out.println("g [Display data log]: ");
}
else if (input.equals("?")){
System.out.println(Assignment6.returnMenu());
}
else
System.out.println("Invalid: ***Type \"?\" to get the commands***");
}
}
}
public class IntTable{
private int row, column, type;
static String log, tFormat;
final int TYPE_DEFAULT = 0;
final int TYPE_NUMBERS = 1;
final int TYPE_SUM = 2;
final int TYPE_MULTIPLY = 3;
final int TYPE_RANDOM = 4;
final int TYPE_POWER = 5;
final int TYPE_FIBONACCI = 6;
String beginRow = " * |";
String divider = "-------";
int count = 1;
public IntTable(){
}
public IntTable(int row, int column, int type){
}
public int getRow(){
return row;
}
public int getColumn(){
return column;
}
public int getType(){
return type;
}
public void setRow(int newRow){
row = newRow;
}
public void setColumn(int newColumn){
column = newColumn;
}
public void setType(int newType){
type = newType;
}
public void printTable(){
int count = 1;
printTableHeader();
for(int i = 1; i <row+1; i++){
System.out.printf("%4d %4s", i, " |");
for (int j = 1; j < column+1; j++)
{
System.out.printf("%4d", count);
count++;
}
System.out.println();
}
}
private void printTableHeader(){
for(int i = 1; i < column + 1; i++)
{
beginRow+=" "+i;
divider+="-----";
}
System.out.println(beginRow);
System.out.println(divider);
}
private void printTableRowID(int ID){
ID = row;
for(int i = 1; i <ID+1; i++){
System.out.printf("%4d %4s", i, " |");
System.out.print(getElement(i, (row-(row-1))));
System.out.println();
}
}
private int getElement(int c, int r){
if(type == 0)
return 0;
else if(type == 1)
return c+column;
else if(type == 2)
return c+ r;
else if(type == 3)
return c*r;
else if(type == 4)
return (int)(1 + Math.random()*10);
else if(type == 5)
return (int)Math.pow(r, c);
else
return r;
}
private int pow(int one, int two){
return (int)Math.pow(one, two);
}
private int fibonacci(int fib){
return fib;
}
private int sum(int add, int addd){
return add + addd;
}
private int multiply(int prod, int product){
return prod * product;
}
private int random(int what, int huh){
return (int)(what + Math.random()*huh);
}
}
the reason why header repeating is because you do not reinitialize variable(beginRow and divider)
when you call printTable Method, variable String beginRow = " * |"; String divider = "-------"; is redefined
you need to reintialize variable(beginRow, divider)
look fllowing code which i modified
private void printTableHeader()
{
for(int i = 1; i < column + 1; i++)
{
beginRow+=" "+i;
divider+="-----";
}
System.out.println(beginRow);
System.out.println(divider);
beginRow = " * |";
divider = "-------";
}
I'm trying to making a program that simulates the card game War.
class Project2
package proj2;
import java.util.Scanner;
public class Project2 {
public static void main( String[ ] args)
{
Scanner keybd = new Scanner( System.in );
// Get player names
System.out.println("Welcome to WAR!!");
System.out.print("Please enter player 1's name: ");
String p1Name = keybd.nextLine();
System.out.print("Please enter player 2's name: ");
String p2Name = keybd.nextLine();
// Get random number generator (RNG) seed and initialize the game
System.out.print ("Please enter the RNG seed for shuffling: ");
long rngSeed = keybd.nextLong();
Game war = new Game(p1Name, p2Name, rngSeed);
int turn = 1;
// While game is being played, print details and results of each turn
while (!war.gameComplete())
{
System.out.printf( "Turn %2d\n", turn);
System.out.println( "-----");
System.out.println( war.nextTurn());
++turn;
}
// All turns complete; print the game results
System.out.println("Game Over!!");
System.out.println(war.gameResult());
}
}
Class Game:
package proj2;
public class Game {
private Deck deck;
private Player player1;
private CardPile p1Deck;
private Player player2;
private CardPile p2Deck;
private int warCount;
private int turns;
public Game(String p1, String p2, long rngSeed)
{
this.deck = new Deck();
deck.Shuffle((int) rngSeed);
this.player1 = new Player(p1, 0, 0);
this.p1Deck = new CardPile(deck.Deal());
this.player2 = new Player(p2, 0, 0);
this.p2Deck = new CardPile(deck.Deal());
this.turns = 1;
this.warCount = 0;
}
public String nextTurn()
{
p1Card = p1Deck.drawCard();
(ERROR)---> String p1Turn = player1.getName() + " shows " + p1Card.cardString();
Card p2Card = p2Deck.drawCard();
String p2Turn = player2.getName() + " shows " + p2Card.cardString();
String winner = "";
if(p1Card.getValue() > p2Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p1Card;
wonCards[1] = p2Card;
p1Deck.addCard(wonCards, 2);
player1.setCardsWon(wonCards.length);
winner = player1.getName() + " wins 2 cards" ;
}
if(p2Card.getValue() > p1Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p2Card;
wonCards[1] = p1Card;
p1Deck.addCard(wonCards, 2);
player2.setCardsWon(wonCards.length);
winner = "/n" + player2.getName() + " wins 2 cards";
}
String warTurn = "";
if(p1Card.getValue() == p2Card.getValue())
{
this.warCount = warCount + 1;
warTurn = "WAR!!";
Card[] wonCards = new Card[8];
while(p1Card.getValue() != p2Card.getValue())
{
wonCards[0] = p1Deck.drawCard();
wonCards[2] = p1Deck.drawCard();
wonCards[4] = p1Deck.drawCard();
Card p1WarCard = p1Deck.drawCard();
wonCards[6] = p1WarCard;
wonCards[1] = p2Deck.drawCard();
wonCards[3] = p2Deck.drawCard();
wonCards[5] = p2Deck.drawCard();
Card p2WarCard = p2Deck.drawCard();
wonCards[7] = p2WarCard;
if(p1WarCard.getValue() > p2WarCard.getValue())
{
p1Deck.addCard(wonCards, wonCards.length);
player1.setCardsWon(wonCards.length);
}
if(p2WarCard.getValue() > p2WarCard.getValue())
{
p2Deck.addCard(wonCards, wonCards.length);
player2.setCardsWon(wonCards.length);
}
}
}
String turnResults = p1Turn + "/n" + p2Turn + "/n" + warTurn + winner;
return turnResults;
}
public boolean gameComplete()
{
boolean result = false;
if(turns == 20) {
result = true;
}
return result;
}
public String gameResult()
{
String p1Result = (player1.getName() + " won " + player1.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String p2Result = (player2.getName() + " won " + player2.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String winner = "";
if(player1.getCardsWon() > player2.getCardsWon())
{
winner = "Winner: " + player1.getName();
}
if(player2.getCardsWon() < player2.getCardsWon())
{
winner = "Winner: " + player2.getName();
}
if(player1.getCardsWon() == player2.getCardsWon())
{
winner = "Game is a draw";
}
String finalResult = ("Game Over!!" + "There were " + warCount
+ "war(s)" + p1Result + "/n" + p2Result + "/n" + winner);
return finalResult;
}
}
When I try to access the class Card, I get a null pointer exception error. I'm not sure what is producing the error.
public class Card {
private char rank;
private String suit;
private int value;
public Card(char rank, String suit, int value)
{
this.rank = rank;
this.suit = suit;
this.value = value;
}
public char getRank()
{
return rank;
}
public String getSuit()
{
return suit;
}
public int getValue()
{
return value;
}
public String cardString()
{
String card = (rank + " of " + suit);
return card;
}
}
I tried googling for solutions, and it tells me to initialize the object before referencing the object. I tried initializing, but it still produces the null pointer exception error.
The error I'm getting is this.
Exception in thread "main" java.lang.NullPointerException
at proj2.Game.nextTurn(Game.java:29)
at proj2.Project2.main(Project2.java:37)
The drawCard() method is from this class.
package proj2;
public class CardPile {
private Card[] playerDeck;
public CardPile(Card[] deck)
{
this.playerDeck = deck;
}
public Card drawCard()
{
Card topCard = playerDeck[0];
Card[] newPlayerDeck = new Card[playerDeck.length - 1];
int counter = 0;
for(int i = 1; i < playerDeck.length; i++)
{
newPlayerDeck[counter] = playerDeck[i];
counter++;
}
this.playerDeck = newPlayerDeck;
return topCard;
}
}
It returns a NULL Point Exception because you are not passing any parameters. Try passing parameters to your constructor.
e.g
Card p1Card = new Card(rank,suit,value);
Card p2Card = new Card(rank,suit,value);
Since p1Card null, then p1Deck.drawCard() returns null - which means playerDeck[0] is null, which means new CardPile(deck.Deal()); creates and empty deck, which means something is wrong in deck.Deal(). By "something is wrong" I mean that it probably creates and returns an array with null values, like: [null, null, null, null, null] (or it might be that the first value is the only one that's null).