Java programming - Class and method - java

I am new to Java programming and I had a task in class.
So the main thing was I had to make a public class named BankAccount with these 3: int number, String owner, int amount.
Then I had to make an array of 10 with this class and fill it up (the owner names were Name1, Name2, etc.).
Then I had to make a String array of 5 with 5 names in it (for example: "James", "Jack", etc.)
and then I had to kind of "modify" the owner names so that my program will attach one of the 5 names randomly to the end of the current owner names.
So it will be like this for example: Name2Jack, Name3James, etc.
I successfully did all of this.
But then.
My teacher told me to make another method which will decide, how many names do I have out of the 10 ownernames in which name X is present.
So I did this:
public static int Count(BankAccount[] accounts, String name){
int number=0;
for (i=0; i<accounts.length, i++){
if(accounts[i].owner.contains(name)==true)
number++;
}
return number;
}
At least if I remember correctly, it was this. Or something similar like that.
And this worked as well.
But then, my teacher said, how would I do it with not .contains but with .equals ?
And if I would do it with that, would I need 1 or 2 "=" marks?
I had no idea what she means, like I dont know how to do it with .equals... because the owner names are like Name1Jack for example..
She told me I would need 1 "=" mark instead of 2, and that I should look after this for the next class.
Can you guys actually tell me what she meant with this ".equals" method instead of the .contains one?
How could I do this with .equals , and I dont get it why would I need 1 "=" mark instead of 2 whatsoever.
Any help would be really appreciated!

It appears that you need to just change this one line:
From:
if (accounts[i].owner.contains(name) == true)
To:
if (accounts[i].owner.equals(name))
Here is a sample code with both variations:
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount[] bankAccounts = new BankAccount[5];
bankAccounts[0] = (new BankAccount(1, "Name1James", 1000));
bankAccounts[1] = (new BankAccount(2, "Name2Jack", 2000));
bankAccounts[2] = (new BankAccount(3, "Name3Henry", 3000));
bankAccounts[3] = (new BankAccount(4, "Name4Jack", 4000));
bankAccounts[4] = (new BankAccount(5, "Name5James", 5000));
System.out.println("Check A:");
System.out.println(BankAccountDemo.Count(bankAccounts, "James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "James"));
System.out.println("Check B:");
System.out.println(BankAccountDemo.Count(bankAccounts, "Name5James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "Name5James"));
}
public static int Count(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.contains(name) == true) {
number++;
}
}
return number;
}
public static int Count2(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.equals(name)) {
number++;
}
}
return number;
}
}
Run output is:
Check A:
2
0
Check B:
1
1

Related

how many time the characters of string are to be found in another string

my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}

Command line arguments [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've created a class called Human that works properly, it takes 2 arguments, age and name, to create a human.
To create a Human with command line arguments, I want to write
java Filename -H "Anna" 25
And it should create a Human with thatname="Anna", and thatage=25, where 25 is an int.
The code I've written is creating a list called Argument, and iterating through it to find -H. I need to do this because I'm going to be using this to create different classes later. I just need help with the syntax on the lines where I've written thename=, and theage=, because I don't know how to get the next item in list, and next-next item in list.
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (String item2: Argument) {
if (item2 == "-H") {
thatname = Argument.get(item2+1)
thatage = Argument.get(item2+2)
Human person = new Human(thatname,thatage);
System.out.println(person);
}
Why not just loop the args?
for ( int i = 0; i < args.length; i++ ) }
if (args[i].equals("-H")) {
i++;
thatName = args[i];
i++;
thatAge = args[i];
}
}
You should add some code to catch if one does not follow the rules you have set. Probably not enough arguments or other things humans do at the keyboard...
thatname = Argument.get(Argument.indexOf(item2)+1);
thatage = Argument.get(Argument.indexOf(item2)+2);
OR you know that 1st element is -H, 2nd element is name and 3rd is age, so you can use below code directly
thatname = Argument.get(1);
thatage = Integer.parseInt(Argument.get(2));
Your code have some problems, let me explain them to you for your assistance.
You cannot compare Strings with == you have to use equals method
in the String to compare between two Strings.
You have to use this for loop for(int i = 0; i < Argument.size();
i++) syntax so that you can iterate from zero to the number of
items in the list.
get method in ArrayList take the index as parameter and return the value at that index.
You can add i += 2 to skip the next two iterations which will
return the name and age value of the human. (It is optional)
Here is the working code:
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
String currentItem;
for (int i = 0; i < Argument.size(); i++) { // it will iterate through all items
currentItem = Argument.get(i); // getting the value with index;
if (currentItem.equals("-H")) {
String thatname = Argument.get(i+1);
String thatage = Argument.get(i+2);
i += 2; // Skipping 2 iterations of for loop which have name and age human.
Human person = new Human(thatname,thatage);
System.out.println(person);
}
}
}
You cannot iterate the list using String. When iterating a list you required a index number like list.get(indexNumber);
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (int i=0;i<args.length;i++) {
if (args[i].trim().equals("-H")) {
i++;
thatname = Argument.get(i);
i++;
thatage = Argument.get(i);
Human person = new Human(thatname,thatage);
System.out.println(person.getName()+" "+person.getAge());
}
Why using array list when you can directly use args? and while you're having only two parameters don't use a for loop access them direclty.
One thing you should know is that String is an object in java so comparing two Strings with == sign will return false even if they have same value (== will compare the id of the object), you should use .equale() function to compare the value of the object.
Check out this code :
public static void main(String[] args) {
if(args.length>0)
{
try{
if (args[0].equals("-H")) {
Human person = new Human( args[1],args[2]);
System.out.println(person);
}
}catch(ArrayIndexOutOfBoundsException exception) {
System.out.println("error with parameters");
}
}else
System.out.println("No command");
}

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

Adding a string to an arraylist through another arraylist's object's method

I am in the process of updating my game to Java, but the only minor bug I have left is this:
Every time a dead player's name is "added" to the dead player name list, it adds the Player object's hashcode instead.
EDIT: Here is a link to a zip folder with the source code:
https://dl.dropboxusercontent.com/u/98444970/KarmaSource.zip
The code in question is the two places where the line gets the player object and gets the object's name. When it is used in println, it works fine and prints the player's name. However, in the second part where it does the same thing, but it prints the hashcode of the player object instead of calling its get_name method and returning the String. I'm not sure if it has to do with the third part, where it adds the "name" to dead player list pdead.
If you'd like a link to the compiled version, let me know. It's compiled under JDK 7 Update 51 64-bit.
EDIT: I got it working, I was originally referencing the players list instead of the pdead list. Thanks to all who contributed to helping. If you still want the game, let me know and I'll put a download link :D
Answering your question:
This code is wrong:
if (karma.pdead.isEmpty())
{System.out.println("None");}
else
for (int index = 0;index < karma.pdead.size();index++)
System.out.println(pdead.get(index));
What is karma? Whatever that is, looks like you're referring to 2 different things there.
Try this:
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (String deadPlayer : pdead) {
System.out.println(deadPlayer);
}
}
Pretty sure this will work :)
Some further, constructive advice:
Your code is breaking pretty much all conventions/good-practices I know in Java. But I am here to help, not to criticize, so let's try to improve this code.
Never keep state in static fields. This is a recipe for causing memory leaks.
your main function won't even compile. Should look like this:
public static void main(String[] args)
Always wrap the body of for loops with braces.
Be consistent: if you open braces in a new line, then do it every time. NEVER write code on the same line as the opening bracket.
GOOD:
public void doSomething()
{
// body
}
GOOD:
public void doSomething() {
// body
}
BAD:
public void doSomething() {
// body
}
public void somethingOther()
{
// inconsistent!
}
public void terribleCode()
{ System.out.println("Never do this"); }
Do not use underscores to separate words. In Java, the favoured convention is to use camelCase. getName(), not get_name().
class names ALWAYS start with a capital letter, whereas variable names generally start with a lower-case letter.
if you're iterating over all items of a list, just use the forEach construct (shown above) not index navigation.
I wanted to check to see if there was some subtle syntax error, so I cut/paste your code into an editor and tried to massage it to get it running. After my massaging, I ran it and it ran fine. Here is the code I ran and the results I got:
Code:
import java.util.ArrayList;
public class Game {
private static ArrayList<Player> players = new ArrayList<Player>();
private static ArrayList<String> pdead = new ArrayList<String>();
public static void main(String[] args) {
// Some Test Data
Player p1 = new Player("George");
p1.setHp(10);
players.add(p1);
Player p2 = new Player("Bob");
p2.setHp(10);
players.add(p2);
// Print Current State of data
System.out.println("Current Players");
for(Player p: players) {
System.out.println(p.getName() + ": " + p.getHp());
}
System.out.println("Dead Players");
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (int index=0; index < pdead.size(); index++) {
System.out.println(pdead.get(index));
}
}
// Kill Bob
p2.setHp(0);
// Do work to add names to dead players data structure
for (int index2=0; index2 < players.size(); index2++) {
if ((players.get(index2).getHp() <= 0) && !(pdead.contains(players.get(index2).getName()))) {
pdead.add(players.get(index2).getName());
}
}
// Print Current State of data
System.out.println("Current Players");
for(Player p: players) {
System.out.println(p.getName() + ": " + p.getHp());
}
System.out.println("Dead Players");
if (pdead.isEmpty()) {
System.out.println("None");
} else {
for (int index=0; index < pdead.size(); index++) {
System.out.println(pdead.get(index));
}
}
}
}
class Player {
private String name = "";
private int hp = 0;
public Player(String n) {
name = n;
}
public String getName() {
return name;
}
public int getHp() {
return hp;
}
public void setHp(int h) {
hp = h;
}
}
Here are the results that code gives me:
javac Game.java
java Game
Current Players
George: 10
Bob: 10
Dead Players
None
Current Players
George: 10
Bob: 0
Dead Players
Bob

Return multiple arrays to the main method

My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.

Categories