How remove element from myType[]? - java

I've got a probleme on my code. I have to use a custom type array ( Colis[] ) and I made my own method to remove element from it :
public Colis[] casiers = new Colis[MAXVALUE];
...
public void removeColis(short num, int mode) {
switch (mode) {
case NUMCASIER:
casiers[num]=null;
break;
case NUMCOLIS:
for (int i=0; i<casiers.length; i++) {
if (casiers[i].noColis==num){
casiers[i]=null;
}
}
default :
break;
}
}
Seems like I don't do the good thing when I do casiers[index]=null;
because I catch a java.lang.NullPointerException.
My question is how should I remove the element contained in casiers[index] ?
Thks

With setting casiers entries to null it is prudent to use
for (int i=0; i<casiers.length; i++) {
if( casiers[i] == null ) continue;
if (casiers[i].noColis==num){
casiers[i]=null;
}
}

In the following code, you try to access casiers[i] without checking if anything actually exists.
for (int i=0; i<casiers.length; i++) {
if (casiers[i].noColis==num){
casiers[i]=null;
}
}
Add a check to see if casiers[i] is not null
for (int i=0; i<casiers.length; i++) {
if(casiers[i] != null && casiers[i].noColis != null){
if (casiers[i].noColis==num){
casiers[i]=null;
}
}
}
This will make sure that casiers[i] is not null, and casiers[i].noColis is not null, before you try to access them in your code.

Related

java equivalent Iterator.remove in c#

The code has migrated from Java to C #.
Java code :
for (List<ItemNY> level : highU.getLevels())
{
Iterator<ItemNY> iterItemset = level.iterator();
while(iterItemset.hasNext())
{
ItemNY c = iterItemset.next();
// Code...
if(c.getU() < min)
{
iterItemset.remove();
highU.decreaseCount();
}
}
}
C# code : (Code written after convert)
foreach (List<ItemNY> level in highU.getLevels())
{
ItemNY c;
using (IEnumerator<ItemNY> iterItemset = level.GetEnumerator())
{
while (iterItemset.MoveNext())
{
c= iterItemset.Current;
//CODE
foreach (TransactionTP transaction in database.getTransactions())
{
int transactionUtility = 0;
int matchesCount = 0;
for (int i = 0; i < transaction.size(); i++)
{
if (c.getItems().Contains(transaction.get(i).item))
{
transactionUtility += transaction.getItemsUtilities()[i].utility;
matchesCount++;
}
}
if (matchesCount == c.size())
{
c.incrementUtility(transactionUtility);
}
}
//END CODE
if (c.getU() < min)
{
iterItemset.remove(); //ERROR
highU.decreaseCount();
}
}
}
}
I want to remove an item from IEnumerator, how can I do this?
Note : The code written in the C # section is more complete, More code is written in the (CODE) to (END CODE) section.
I want to remove an item from IEnumerator, how can I do this?
Easy: you don't.
I do not know Java, but that idea does not make sense in .NET. As you can read in the documentation:
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
As it is also mentioned, foreach should be used instead of IEnumerator<T> directly:
foreach (List<ItemNY> level in highU.getLevels())
{
foreach (var item in level)
{
if (item.getU() < min)
{
level.Remove(item); //Error, you are modifying a collection being enumerated
highU.decreaseCount();
}
}
}
You would have to put the elements that match the filter in a new collection so you could remove them from level.
foreach (List<ItemNY> level in highU.getLevels())
{
var filteredItems = new List<ItemNY>();
foreach (var c in level)
{
foreach (TransactionTP transaction in database.getTransactions())
{
int transactionUtility = 0;
int matchesCount = 0;
for (int i = 0; i < transaction.size(); i++)
{
if (c.getItems().Contains(transaction.get(i).item))
{
transactionUtility += transaction.getItemsUtilities()[i].utility;
matchesCount++;
}
}
if (matchesCount == c.size())
{
c.incrementUtility(transactionUtility);
}
}
if (c.getU() < min)
{
filteredItems.Add(c);
highU.decreaseCount();
}
}
foreach (var item in filteredItems)
{
level.Remove(item);
}
}
If the true goal is to remove items from the list then I would use List.RemoveAll, with conditions defining which to remove.
If you need the extra counter update then you take a size before and after. Though at least in the presented case there is no need for the decreaseCount method, as it appears to track size of the list, so I would drop the method, and rely on the list Count.

App is crashing when I convert string to int

I use two dimensional array and suppose I want to convert a string to int in a specific element
like that arr[0][1]="12";. I am using this
int id=0; String[][] description=new String[obj.length][];
String[] temp;
for(int i=0; i<obj.length; i++) {
da[i]=obj[i].toString(); temp=da[i].split(",");
description[i]=new String[temp.length];
for(int j=0; j<temp.length; j++) {
// id=new String[temp.length];
description[i][j]=temp[j];
if(j==0) {
try {
id=Integer.parseInt(description[i][j]);
}
catch(NumberFormatException nfe) { // Log exception. }
//id=Integer.parseInt(description[i][j].toString());
Toast.makeText(getApplicationContext(),id, Toast.LENGTH_SHORT).show();
}
}
But it gives null pointer exception.
check if its not null then cast to integer:
try {
if(description[i][j]!=null && description[i][j].length()>0){
id=Integer.parseInt(description[i][j]);
Toast.makeText(getApplicationContext(),id, Toast.LENGTH_SHORT).show();
}
}
instead of
try {
id=Integer.parseInt(description[i][j]);
}
i hope its work but description[i][j] must returns string.
if id getting value then print toast.otherwise no toast print..

for loops and if statement error occuring

I can't figure out why I get the error:
java.util.NoSuchElementException null(in java.util.Scanner)
in my method:
public void processTransactions(Scanner transFile){
while (transFile.hasNext()){
for(i = 0; i < ids.length; i++){
finalInventory[i] = startingInventory[i];
if(ids[i] == transFile.next()){
finalInventory[i] += transFile.nextInt();
}
}
}
}
this is my construtor:
public SoftDrinkInventory(Scanner inventoryFile) {
initializeString(names);
initializeString(ids);
initializeInt(startingInventory);
initializeInt(finalInventory);
initializeInt(transactionCounts);
while (inventoryFile.hasNext()){
names[i] = inventoryFile.next();
ids[i] = inventoryFile.next();
startingInventory[i] = inventoryFile.nextInt();
i++;
}
}
All variables have been declared previously in the class.
I'm guessing a little, but I think your code was supposed to be this.
public void processTransactions(Scanner transFile){
while (transFile.hasNext()){
String key = transFile.next();
int value = transFile.nextInt();
for(i = 0; i < ids.length; i++){
finalInventory[i] = startingInventory[i];
if(ids[i].equals(key)){
finalInventory[i] += value;
}
}
}
}
You only want to do the next() and the nextInt() once per iteration of the while loop. Currently, you are repeating the next() in every iteration of the for loop, which really isn't what you want.
Note that this isn't the most efficient solution to your problem, but it will take away your error.
Also, you haven't specified the type of ids, but I've assumed that it's a String[].
You are calling hasNext() but using nextInt() ... One solution is to use,
while (transFile.hasNextInt()){
// As before.
}
Another is to skip anything that isn't an int, perhaps like so
while (transFile.hasNext()){
if (!transFile.hasNextInt()) {
transFile.next();
continue;
}
// As before.
}

Java - object existence dilem

I wrote the following, this is a toString of a Country class that has City class in same package, and _cities is an array represents the cities within my Country:
**EDITED:**
public String toString(){
String allCitiesData = ""; //must be initialized
for(int i=0;this._cities[i] != null;i++)//run all over the cities until reach the end(null cell)
{ //concat new city to the string and adds a new line between
allCitiesData = allCitiesData.concat(this._cities[i].toString()+"\n\n");
}
return allCitiesData;
}//toString method
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
Point referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}//citiesNorthOf method
But, when I run it, it shows a single error only on this line:
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
And the Eclipse says: "referenceCityCenter cannot be resolved to a variable".. any suggestions ?
Thanks !!
You have declared referenceCityCenter in a scope which is not visible to that line of your code. Try declaring it at the beginning of the method (and control too if it is null when it arrives to your validation .isAbove()! :P )
referenceCityCenter is out of scope. Put it outside of your if statement and make sure you check for null afterwards like follows:
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
Point referenceCityCenter = null;
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (referenceCityCenter !- null && this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}

constructing a 2D array and assigning

package homework3;
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix (int row, int col)
{
if(row > 0 & col > 0)
{
makeDoubMatrix(1,1);
}
else
{
row = 1;
col = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
int k = tempArray.length;
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
if(k== tempArray[i].length)
{
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
}
This is what i was supposed to start my assignment with:
Write a class called DoubleMatrix in which you declare a 2-dim. array of doubles (I'm calling it doubMatrix) as a private instance variable. Include the following constructors or instance methods (NO static METHODS HERE):
constructor with an int for the first dimension (be sure it's > 0, set to 1 if not), and an int for the second dimension (be sure it's > 0, set to 1 if not) and call the makeDoubMatrix private instance method (see below)
another constructor with a 2-dim. array of doubles as its parameter (assign if parameter isn't null AND if each row has the same length as the other rows), otherwise, call makeDoubMatrix with 1, 1)
can someone check that if I did the check in second constructor right? Also I left out the assigning statement in the second if because I don't know what to assign can anyone tell me what to assign since the problem only say assign but didn't say to assign to what value.
You would have to check for each row first, whether they are of same length or not. You can maintain a boolean flag variable, which you can set to false as soon as you see that the current row is not the same length as the next row.
You can try the below code, and test whether it works: -
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null)
{
boolean flag = true;
for(int i = 0; i < tempArray.length - 1;i++)
{
// Check each row with the next row
if(tempArray[i].length != tempArray[i + 1].length)
{
// as you find the row length not equal, set flag and break
flag = false;
break;
}
}
if (flag) {
doubleMatrix = tempArray;
} else {
makeDoubleMatrix(1,1);
}
} else {
makeDoubleMatrix(1, 1);
}
}
public DoubleMatrix(double[][] tempArray)
{
//Calling tempArray.length if tempArray is null will get you an error
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
for(int j=0;j<tempArray[i].length;j++)
{
doubleMatrx[i][j] = tempArray[i][j];
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
Also in Java a 2D array will always have the same number of columns in each row since it's declaration is something like int bob[][] = new int[a][b]

Categories