I guess this is a simple question but I can't find an answer on either Google or Stack Overflow. I am new to Java and I hope you can help me. I'm sorry in advance if I use the wrong terminology at any point when writing my question and code.
My question is if there is any way to write a code that repeats an external method call?
The method I am calling is shootWeapon which exists in a class called Weapon. I'm calling that method from another method called shootWithWeapon which exists in a class called Soldier. My class Soldier has an inventory of weapons in ArrayList<Weapon> called weaponList. I would like to write a code that repeats listWeapon.shootWeapon() as many times as the user given shootWithWeapon parameter usedAmmo. My current code is working but it's only decreasing the ammo with 1 (since it's specified in the shootWeapon method).
This is my method in class "Soldier".
public void shootWithWeapon(String weaponChoice,int usedAmmo)
int index = 0;
while(index < weaponList.size()){
Weapon listWeapon = weaponList.get(index);
String usedWeapon = listWeapon.getName(); //returns weapon name
int xBullets = weaponList.getBulletAmount(); //returns amount of bullets in object
if(weaponChoice.equals(usedWeapon) && usedAmmo < xBullets) {
listWeapon.shootWeapon(); //This is the method I want to repeat * usedAmmo
System.out.println("Your weapon have been used. You have " + weaponList.getBulletAmount() + " bullets left".); }
index++;
}
}
This is the method I'm calling in class "Weapon".
public void shootWeapon()
{
bulletAmount=bulletAmount - 1;
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
arraylist displays object address not actual object , program usesinheritance where salesEmployee is the super class and salesAgent and salesPerson are the subclasses.
import java.util.Scanner;
import java.util.ArrayList;
public class tester {
public static void main(String[]args ) {
ArrayList <salesEmployee> listemps= new ArrayList <salesEmployee>();
Scanner user_input= new Scanner(System.in);
salesPerson emp1 = new salesPerson();
emp1.setName("Frank Long");
emp1.setppsNumber(65783);
System.out.println("Enter total value of sales earned by Frank Long");
double valeSale;
valeSale=user_input.nextDouble();
emp1.setvalSale(valeSale);
emp1.getCommission();
listemps.add(emp1);
for ( int j=0; j<listemps.size(); j++ )
System.out.println("element " + j + ": " + listemps.get(j) );
}
}
This is my salesPerson class
public class salesPerson extends salesEmployee{
public salesPerson() {
}
public salesPerson(String name, int ppsNumber, double valSale, double commission) {
super(name, ppsNumber,valSale,commission);
}
public void getCommission() {
commission=valSale*0.15;
}
public String toString2() {
return toString1()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
I'll make it more elegant later for now I am just trying to get it to work
Updated: Based on the comments to my answer, there is a different issue at play. Here's what was added in the comments:
Enter total value of sales earned by Frank Long 22.00
Exception in thread "main" java.lang.StackOverflowError at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) – lucylio 5 mins ago
Is what comes up – lucylio 5 mins
In order for something reasonable to be displayed, you need to implement toString method in your class. You do have toString1 and toString2, but seemingly, no toString. (You haven't posted the code for salesEmployee class - but most likely it also doesn't have toString implementation).
In absence of toString, default Object.toString is called, which displays the address of the object.
Implement toString - and you'll see your results.
UPDATE: As the error you indicated doesn't correspond to the code, I'll go on a whim and suggest that, probably your toString2 method is actually toString and your toString1 method is actually a toString defined in your parent class, i.e. salesEmployee.java. In this case, instead of calling toString() from inside your toString method, use super.toString() instead:
public class salesPerson extends salesEmployee {
...
public String toString2() {
return super.toString()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.
Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.
You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}
Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}
This question already has answers here:
Randomly select an item from a list
(5 answers)
Closed 4 years ago.
I'm learning Java and I'm having a problem with ArrayList and Random.
I have an object called catalogue which has an array list of objects created from another class called item.
I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator = new Random();
private ArrayList<Item> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Item>();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
When I try to compile I get an error pointing at the System.out.println line saying..
'cannot find symbol variable anyItem'
anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.
Might want to re-write it like:
import java.util.ArrayList;
import java.util.Random;
public class Catalogue
{
private Random randomGenerator;
private ArrayList<Item> catalogue;
public Catalogue()
{
catalogue = new ArrayList<Item>();
randomGenerator = new Random();
}
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item item = catalogue.get(index);
System.out.println("Managers choice this week" + item + "our recommendation to you");
return item;
}
}
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
Item randomItem = catalogue.get(index);
System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
return randomItem;
}
The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...
Here you go, using Generics:
private <T> T getRandomItem(List<T> list)
{
Random random = new Random();
int listSize = list.size();
int randomIndex = random.nextInt(listSize);
return list.get(randomIndex);
}
You must remove the system.out.println message from below the return, like this:
public Item anyItem()
{
randomGenerator = new Random();
int index = randomGenerator.nextInt(catalogue.size());
Item it = catalogue.get(index);
System.out.println("Managers choice this week" + it + "our recommendation to you");
return it;
}
the return statement basically says the function will now end. anything included beyond the return statement that is also in scope of it will result in the behavior you experienced
try this
public Item anyItem()
{
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
And I strongly suggest you to get a book, such as Ivor Horton's Beginning Java 2
anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
You havent the variable anyItem initialized or even declared.
This code:
+ anyItem +
means get value of toString method of Object anyItem
The second thing why this wont work. You have System.out.print after return statement. Program could never reach tha line.
You probably want something like:
public Item anyItem() {
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
btw: in Java its convetion to place the curly parenthesis on the same line as the declaration of the function.
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
See https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57
public static void main(String[] args) {
RandomList<String> set = new RandomList<>();
set.add("a", 10);
set.add("b", 10);
set.add("c", 30);
set.add("d", 300);
set.forEach((t) -> {
System.out.println(t.getChance());
});
HashMap<String, Integer> count = new HashMap<>();
IntStream.range(0, 100).forEach((value) -> {
String str = set.raffle();
count.put(str, count.getOrDefault(str, 0) + 1);
});
count.entrySet().stream().forEach(entry -> {
System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
});
}
Output:
2.857142857142857
2.857142857142857
8.571428571428571
85.71428571428571
a: 2
b: 1
c: 9
d: 88
The solution is not good, even you fixed your naming and unreachable statement of that print out.
things you should pay attention also
1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.size().
you didn't handle multithread, you might get index out of bound exception
Here's a better way of doing things:
import java.util.ArrayList;
import java.util.Random;
public class facultyquotes
{
private ArrayList<String> quotes;
private String quote1;
private String quote2;
private String quote3;
private String quote4;
private String quote5;
private String quote6;
private String quote7;
private String quote8;
private String quote9;
private String quote10;
private String quote11;
private String quote12;
private String quote13;
private String quote14;
private String quote15;
private String quote16;
private String quote17;
private String quote18;
private String quote19;
private String quote20;
private String quote21;
private String quote22;
private String quote23;
private String quote24;
private String quote25;
private String quote26;
private String quote27;
private String quote28;
private String quote29;
private String quote30;
private int n;
Random random;
String teacher;
facultyquotes()
{
quotes=new ArrayList<>();
random=new Random();
n=random.nextInt(3) + 0;
quote1="life is hard";
quote2="trouble shall come to an end";
quote3="never give lose and never get lose";
quote4="gamble with the devil and win";
quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
quote13="No one can make you feel inferior without your consent.";
quote14="Let him who would enjoy a good future waste none of his present.";
quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
quote20="It is our choices, that show what we truly are, far more than our abilities.";
quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
quote22="The successful warrior is the average man, with laser-like focus.";
quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
quote27="Don’t let the fear of losing be greater than the excitement of winning.";
quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
quote29="There is nothing permanent except change.";
quote30="You cannot shake hands with a clenched fist.";
quotes.add(quote1);
quotes.add(quote2);
quotes.add(quote3);
quotes.add(quote4);
quotes.add(quote5);
quotes.add(quote6);
quotes.add(quote7);
quotes.add(quote8);
quotes.add(quote9);
quotes.add(quote10);
quotes.add(quote11);
quotes.add(quote12);
quotes.add(quote13);
quotes.add(quote14);
quotes.add(quote15);
quotes.add(quote16);
quotes.add(quote17);
quotes.add(quote18);
quotes.add(quote19);
quotes.add(quote20);
quotes.add(quote21);
quotes.add(quote22);
quotes.add(quote23);
quotes.add(quote24);
quotes.add(quote25);
quotes.add(quote26);
quotes.add(quote27);
quotes.add(quote28);
quotes.add(quote29);
quotes.add(quote30);
}
public void setTeacherandQuote(String teacher)
{
this.teacher=teacher;
}
public void printRandomQuotes()
{
System.out.println(quotes.get(n++)+" ~ "+ teacher);
}
public void printAllQuotes()
{
for (String i : quotes)
{
System.out.println(i.toString());
}
}
}