Adding a Value to an Array - java

I have a method which needs to add the provided bank account to an array which I have created:
public boolean addAccount (BankAccount newAccount[]) {
if (numAccounts == 0) {
return false;
}
else {
return true;
for(int counter=0; counter<newAccount.length; counter++)
newAccount[counter] += accounts;
}
}
it is tested by this method:
public static boolean test5() {
System.out.println("Test5: add an account to a customer.");
BankAccount b = new BankAccount();
Customer c1 = new Customer("Alice", "Smith");
customerCounter ++;
if (!c1.addAccount(b))
return false;
return c1.toString().equals("Alice Smith, " + c1.getCustomerID() + "\n" + b.toString() + "\n");
}
However I am getting an error which eclipse does not have a solution for in this line:
newAccount[counter] += accounts;

First of all you need to improve the code quality. Re-design your function and data structure.
In the addAccount function, where did you derive/manipulate 'numAccounts'?
In method parameter, use List instead of array 'BankAccount newAccount[]'. Use like (List accounts). Then you can use accounts.add() method.
what is the definition of 'accounts'?
Do you really need to return anything from this method?
after return statement, no code will be executed. move 'return' statement as the last statement.
Paste the full code to get idea about overall structure.

If u just want to see how a new value can be added to an array then here it is...
int myArray[]={10,20,30};
int newNumber=200; //new value to be added
/*Size of an array doesn't change once it is initialized,so a new Array must be
created (with new Size )to add new values.*/
int newArray[]=new int[myArray.length+1];
//The newArray will have {0,0,0,0};
// Now copy all the data from previous array to new array.
for(int i=0;i<myArray.length;i++)
newArray[i]=myArray[i];
//Now the content of newArray is {10,20,30,0}
newArray[newArray.length-1]=newNumber;
//Now the final content of newArray is {10,20,30,200}.
Now,Having said that, I agree with #Turing85 and #Shafiul.With your above code,you will eventually get unreachable code and also Type Incompatible errors and yes,kindly redesign your code.

Related

Why does my compiler say that my return statement is missing?

I put in the return statement for both cases, if and else
but it's still says that the return statement is missing
What's wrong with my code?
public static getNext(){
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for(int x=0; x<i.length; x++){
copy.add(i[x]);
}
if(copy.size() < 1){
return "NONE";
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls);
}
}
else{
rolls = dice.nextInt(copy.size());
return copy.get(rolls);
copy.remove(rolls); <--- UNREACHABLE
}
Your compiler probably missed the return statement due to unreachable line of code after the return.
Also, you haven't declared the returned class. There should be:
public static <return type> methodName(<parameters>) {
<body>
}
Q: How could I remove the copy.get(rolls) after returning it? Is there a way?
A: Basically the question is about the concept of functions. Function is a piece of code which performs some logic and then, based on it returns something. Return statement is the last thing that happens in the function.
You can also have a block of code which doesn't return anything, but takes parameters. These are called procedures. Anyway, in Java we call both of them: functions and procedures methods.
You have some misunderstood in your code :
First when you make return the method should return something
Second you can't specify any kind of statement after your return
Third you have to store your return value that you want to remove it and return it in a separate variable
Your code should look like this :
public static String getNext() {
//-------------^^------------return type
ArrayList<String> copy = new ArrayList<String>();
Random dice = new Random();
int rolls;
for (int x = 0; x < i.length; x++) {
copy.add(i[x]);
}
if (copy.size() < 1) {
return "NONE";
} else {
rolls = dice.nextInt(copy.size());
String s = copy.get(rolls);//<<----------put the val you want in separate variable
copy.remove(rolls);//<<-----------remove your val
return s;//<<-----------return your val
}
}
Note
Like #BackSlash mention in comment, it is useless to remove your val from your list, because it will not used after you get out of your method, so if you are using this List in another place you have to declare it outside your method for example :
private static ArrayList<String> copy = new ArrayList<String>();
public static String getNext() {
//ArrayList<String> copy = new ArrayList<String>();//<<<-------------useless position
....

Java arrays - How to go through List and set specific value

First i add new Popotnik in List popotnik depending on how big it is, which is working fine - function prostaMesta. Then i want to go through list popotnik and set popotnik value depending on where it is in for, but value of i will always be 0 everytime it is being called. Also i have break there as i only want to set one popotnik at the time. How should i increment (i) while having some sort of break in there?
Also if(popotnik.get(i) == null){} is not being called, but values inside popotnik are null(s)
private List<Popotnik> popotnik = new ArrayList<Popotnik>();
public void prostaMesta(List<Popotnik> popotnik, int sedez){
stanovanje.setPostle(sedez);
for(int i=0; i<stanovanje.getPostle(); i++){
popotnik.add(new Popotnik());
}
System.out.println(popotnik);
}
public void dodajPotnika(List<Popotnik> popotnik, Popotnik popotnik2){
for(int i=0; i<popotnik.size(); i++){
if(popotnik.get(i) == null){
setPopotnik(popotnik, i);
popotnik.set(i, popotnik2);
break;
}
}
System.out.println(getPopotnik());
}
public void setPopotnik(List<Popotnik> popotnik, int i){
this.popotnik = popotnik;
}
public List<Popotnik> getPopotnik(){
return popotnik;
}
Main class:
List<Popotnik> alPopotnik = new ArrayList<Popotnik>();
if(x.equals("p")){ //inside of a loop when prostaMesta() is being called
potovanje.prostaMesta(alPopotnik, sedez);
}
`if(x.equals("d")){` //inside of a loop when dodajPotnika() is being called
System.out.println("Vnesi ime: ");
String ime = skener.next();
Popotnik popotnik = new Popotnik(ime);
potovanje.dodajPotnika(alPopotnik, popotnik);
}
The if(popotnik.get(i) == null) is never true because objects on the list are not null. You initialize them in the for loop in prostaMesta.
If you have some fields inside the Popotnik class then they are null, but object itself is not.
You would need to do something like popotnik.get(i).getName() == null.
Besides, if you only want to add a number at the end of popotnik's name then it isn't necessary to initialize a list with empty objects.
You could just add objects to list using a different constructor.
For example popotnik.add(new Popotnik("Popotnik"+(popotnik.size()+1))).
It's not pretty but I think initialization like this here is not necessary.

How to pull specific data from an object in an arraylist

Ok, not sure if the title worded that correctly but say I have three objects with two strings of data each(Lets say a stateName and a cityName) stored into an arraylist. Is it possible to enter in a state name in as a string variable(call it searchStateName), then have a method search through the objects in the list and compare searchStateName to the stateName inside each object in the arraylist, and when a match is found have it return the cityName that is inside the same object as the matching stateName?
I am trying to do something similar currently and would like to figure it out myself, but I have been working on this for the past hour and am completely lost. Could anyone point me in the right direction?
This is the approach. Say you have a class called SC and you have two instance variables in it and getters and setters for them. You need to initialize 3 objects of them inside your main:
SC a = new SC("Illinois ","Chicago ");
SC b = new SC("Michigan ","Detroit");
SC c = new SC("New York"," New York");
And then create an ArrayList of object SC and add those 3 objects of SC to that ArrayList.
ArrayList<SC> list = new ArrayList<SC>();
list.add(a);
list.add(b);
list.add(c);
Now call the method that search for a state name and returns the city name if it finds it:
this.searchStateName("Illinois");
The actual implementation of this method with for-each loop:
public String searchStateName(String stateName){
String result = "No city found.";
for (SC sc : list )
if (sc.getStateName().equalsIgnoreCase(stateName)){
result = sc.getCityName();
break;
}
}
return result;
}
If you are not comfortable with for-each loop then you can use the regular for loop below. I commented out on purpose. But it will work correctly and give you the correct city name.
//public String searchStateName(String stateName){
// String result = null;
// for (int i = 0; i < list.size(); i++){
// if (list.get(i).getStateName() .equalsIgnoreCase(stateName)){
// result = list.get(i).getCityName();
// break;
// }
// }
// return result;
//}
And thats it. Let me know if you need help further.

Variable might not have been initialized when dealing with array

In a method I created I am trying to create is meant to return an array of user inputted strings. The issue that I am having it the compiler is saying that userData may not be initialized at userData[i]=tempData; and at return userData;. I am unsure why this error is occuring, and would like some feedback.
public String[] getStringObj() {
int i = 0;
String tempData;
String[] userData;
Boolean exitLoop = false;
System.out.println("Please list your values below, separating each item using the return key. To exit the input process please type in ! as your item.");
do {
tempData = IO.readString();
if (tempData.equals("!")) {
exitLoop=true;
} else {
userData[i] = tempData;
i++;
}
} while (exitLoop == false);
return userData;
}
In the interests of improving code quality:
You don't need that exitLoop flag; just do
while(true) {
String input = IO.readString();
if(input.equals("!")) {
break;
}
/* rest of code */
}
Since you seem like you want to just add stuff to an array without bounds, use an ArrayList instead of an array (added bonus, this gets rid of i too):
List<String> userData = new ArrayList<String>();
...
userData.add(line);
If you do these two things, your code will be much more concise and easy to follow.
Your userData is not initilaized and you are attempting to use it here userData[i]=tempData; before initialization.
Initialize it as
String[] userData = new String[20];
//20 is the size of array that I specified, you can specify yours
Also in your while condition you can have while(!exitLoop) instead of while(exitLoop==false)
You didn't initialize the String[]. Just do String[] userData = new String[length]. If you are unsure of the length, you may just want to use an ArrayList<String>.

ArrayList warning- warning: [unchecked] unchecked call to add(E), also file will not run

I've been trying to get this code to work for what feels like an age at this stage. it is meant to compute prime numbers in a range, and I've written a method to print them. Unfortunately the code will not compile, citing the warning:
"warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List"
--I understand from googling that this warning is for not declaring what types of values should be in your erray, but I have done this, and the error only seems to come about when I try to use the .add() function on my array list.
and when I try to run it it gives a somewhat more scary error of
"Static Error: Undefined name 'PrimeNumbers'
I think I've gone code-blind at this point and despite several attempts cannot find out what I am doing wrong.
import java.util.*;
public class PrimeNumbers {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumbers primeNumberList = new PrimeNumbers(50);
primeNumberList.print(); //use our new print method
}
public PrimeNumbers (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
public void print() //add this printout function
{
int i = 1;
Iterator iterator = listOfPrimeNumbers.listIterator();
while (iterator.hasNext())
{
System.out.println("the " + i + "th prime is: " + iterator.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
Change this line
private List listOfPrimeNumbers; //add a member variable for the ArrayList
to
private List<Integer> listOfPrimeNumbers; //add a member variable for the ArrayList
This will elimiate the warning.
Bonus - you may want to use the enhanced for loop inside the print method as an alternative approach:
public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}
You've decalred primeNumbers to be an untyped List but then created an ArrayList of Integer. Change the declaration of primeNumbers to:
private List<Integer> listOfPrimeNumbers;
The for loop you are using to set all the isPrimeNumber to true doesnt work, the condition should be i<=initialCapacity or even better use:
Arrays.fill(isPrimeNumber, true);
In your print method I wouldnt bother using an iterator and keeping track of the int i, just use a normal for loop.
Without knowing what command you are using to build the code and then try and run it, it is hard to diagnose your runtime error. Make sure your command window is in the same directory as your .class file.

Categories

Resources