App is crashing when I convert string to int - java

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..

Related

How to Search ArrayList For Integer and Remove It If It Exists In Java

In my program I have to to be able to remove items from an arrayList. The user inputs a number and then if it exists in the arrayList it is removed. When I press the remove button the program would crash if it weren't for my try and catch statements, does anyone know what I should change for the removal to work properly?
public class SumElements extends javax.swing.JFrame {
ArrayList <Integer> values = new ArrayList();
...
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
//declare variables
int searchVal = Integer.parseInt(valueInput.getText());
//search array for inputed value
int index = Collections.binarySearch(values, searchVal);
if (index >= 0){
//clear outputArea
outputArea.setText(null);
outputLabel.setText(null);
//remove from array
values.remove(valueInput.getText());
//display updated values
Collections.sort(values);
for (int i = 0; i < values.size(); i++)
{
outputArea.setText(outputArea.getText() + values.get(i) + "\n");
}
//clear input
valueInput.setText(null);
}
else {
outputLabel.setText("Data not found. Please try again.");
}
}
//set default
catch (NumberFormatException a)
{
outputLabel.setText("Please input a valid number.");
}
}

How remove element from myType[]?

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.

Replace ArrayList Values with new String Values

i have a arraylist called arrstatus which has a set of Numeric values stored dynamically.
I have to Replace those Numeric Values with Unique String values.
I tried various methods it doesnt seem to be working
i tries Set method, didnt work,
// int[] flags = new int[arrstatus_old.size()];
int [] c = new int [arrtaskid.size()];
Toast.makeText(MyTask.this, "C:"+c, Toast.LENGTH_LONG).show();
for(int j=1;j<= c.length;j++)
{
if(arrstatus.get(j).equals("1"))
{
arrstatus_old.set(j, "Saved");
}
else if(arrstatus.get(j).equals("2"))
{
arrstatus_old.set(j, "Assigned");
}
else if(arrstatus.get(j).equals("3"))
{
arrstatus_old.set(j, "Accepted");
}
else if(arrstatus.get(j).equals("4"))
{
arrstatus_old.set(j, "Rejected");
}
}
I am not getting the size of the arrastutus, it says 0
and hence no values are getting replaced,
any better idea to replace the value.?
Your ArrayList in which 1 i.e. numbers are stored should store numbers in String format.
Your arrayList should be like ArrayList<String>
ArrayList<String> arrstatus = new ArrayList<String>();
arrstatus.add("1");
arrstatus.add("2");
arrstatus.add("3");
As you are checking in arraylist using equals you'll have add numbers as a String.
if (arrstatus.get(i).equals("1")) {
arrstatus.set(i, "Saved");
}if (arrstatus.get(i).equals("2")) {
arrstatus.set(i, "Assigned");
}if (arrstatus.get(i).equals("3")) {
arrstatus.set(i, "Accepted");
}
and so on...
ArrayList<String> arrstatus = new ArrayList<String>();
arrstatus.add("1");
arrstatus.add("2");
arrstatus.add("3");
arrstatus.add("4");
for(int j=0;j< c.length;j++)
{
if(arrstatus.get(j).equals("1"))
{
arrstatus_old.set(j, "Saved");
}
else if(arrstatus.get(j).equals("2"))
{
arrstatus_old.set(j, "Assigned");
}
else if(arrstatus.get(j).equals("3"))
{
arrstatus_old.set(j, "Accepted");
}
else if(arrstatus.get(j).equals("4"))
{
arrstatus_old.set(j, "Rejected");
}
}

char array to int array conversion in java generates null pointer exception

I am trying to run the following HillCipher program but it is terminated after the line of conversion of char array to int array and after compilation of that code it shows me null pointer exception.It works fine if I replace int array with int variable,but I need int array in this code to encrypt the data:
try{
do//key
{
System.out.println("Enter Key of length 4 character : ");
sKey=(new BufferedReader(new InputStreamReader(System.in))).readLine();
cKey=new char[2][2];
}while(!checkKey());
}
catch(Exception e)
{}
}
boolean checkKey()
{
boolean flag=true;
if(sKey.length()!=4)
flag=false;
int k=0;
int temp;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
cKey[i][j]=sKey.charAt(k);
k++;
iKey[i][j]=(int)cKey[i][j]; //program is terminated after this line
iKey[i][j]-=97;
if(cKey[i][j]<97 || cKey[i][j]>122)
{
flag=false;
break;
}
}
if(flag==false)
{
System.out.println("flag: "+flag);
break;
}
}
int d;
if((d=iKey[0][0]*iKey[1][1]-iKey[1][0]*iKey[0][1])==0)
flag=false;
if(flag==false)
System.out.println("Invalid Key!! ");
else
keygen(d);
return flag;
}
void keygen(int d)
{
if (d<0)
d*=-1;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
if(i==0 && j==0)
iDKey[i][j]=iKey[1][1]/d;
else if(i==1 && j==1)
iDKey[i][j]=iKey[0][0]/d;
else
iDKey[i][j]=-iKey[i][j]/d;
}
}
}
String encrypt()
{
int l;
if(sPlainTxt.length()%2==0)
l=sPlainTxt.length();
else
l=sPlainTxt.length()+1;
int temp1,temp2,ans;
for(int i=0;i<l;i+=2)
{
temp1=(int)cPlainTxt[i]-97;
temp2=(int)cPlainTxt[i+1]-97;
ans=iKey[0][0]*temp1+iKey[0][1]*temp2;
System.out.println(ans);
ans%=26;
ans+=65;
cCipherTxt[i]=(char)ans;
cCipherTxt[i+1]=(char)((iKey[1][0]*temp1+iKey[1][1]*temp2)%26+65);
}
sCipherTxt=new String(cCipherTxt);
return sCipherTxt;
}
}
You never assign a value to iKey, so it has its initial default value of null - it's as simple as that. You need to create a new array, e.g.
// Given that you've hard-coded the length of cKey as well...
iKey = new int[2][2];
I'd also strongly urge you not to catch exceptions like this:
catch(Exception e)
{}

Logic of deleting in Java

I cant figure out how to start a method to delete a specific entry stored in an array...
I used to do this:
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
}
}
}
but I was advised not to assign the entry[i] to null because it will ruin my entries...
I have no idea how to code it in another way...
What should I need to do is:
I need to delete a specific entry from an array
please help...
also... its output was error it says:
Exception in thread "main" java.lang.NullPointerException
at AddressBook.viewAll(AddressBook.java:62)
at AddressBook.main(AddressBook.java:36)
Java Result: 1
This is my code in my main program:
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
for (int i = 0; i < counter; i++) {
addText = addText + entry[i].getInfo() + "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to find: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void editEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
Assigning the values to null is going to be the easiest practice. If you're really picky, you could resize the array, but that would be rather pointless. Just keep a separate size counter and decrement it each time you set something to null.
Another reason you're getting a null pointer exception is that you have to consider what's happening when you're replacing values in your array with null but still iterating by counter. You're going to be left with holes in your array upon deletion. The first solution would be to bypass null values altogether, and just shift your array down (somewhat of an expensive operation). The second would be to alter your methods to take those null values into consideration. Example:
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) break;
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
I don't have a compiler on this computer, so consider it more of psuedo-code. But the idea is that the counter is only keeping track of how many non-null values you have in your address book, and that these null values could be in random places of your array. I added the nonNull integer as a local counter to keep track of how many values you've encountered that aren't null (so you aren't forced to run through the entire address book). Then, I added the if statement to ensure that the value at entry[i] isn't a null value (trying to invoke getInfo() on a null value is what's giving you that error). Lastly, I added the if statement to break the loop if you've encountered all of the non-null values you have stored. Hope this helps. (Also it may be worth considering a LinkedList to eliminate the null values all together).
Actually, for simplicity's sake, you probably are much better off using a LinkedList, unless you are required to use an array, since you would need to alter all of your methods to take null spaces in your array into account. Assuming you're familiar with LinkedLists of course.
Arrays are immutable. You can change the value for a particular index in the array but you can't change the array size itself. To "delete", you could do:
myArray[index] = null;
And just treat null values as unset/deleted entries.
Assigning to null (currently what you are doing) is the proper thing to do. That will eliminate the reference to the object at that index and allow it to be garbage collected.
Replace entry[i] = null; with this:
System.arraycopy(entry, i + 1, entry, i, counter - i - 1);
--counter;
entry[counter] = null; // optional; helps with garbage collection
--i; // required to not skip the next element
(I'm assuming here that counter is the number of valid entries in entry. This will leave no null entries among the first counter elements of entry (assuming that there weren't any to start with).
Further thought: If you need the array length to always match the number of valid entries, you'll have to re-allocate the array and copy the values over. Just use arraycopy to copy entries from 0 through i-1 and from i+1 to counter-1 into the new array and then assign it to entry. This isn't particularly efficient and is best avoided if possible.
Better to this is List which has remove() method. But if you really want use Array I recommend you change Array to List and then remove all values, after it you can always change List to Array
import javax.swing.JOptionPane;
public class Test {
private static User[] entry = new User[] { new User("Gil"),
new User("Bil"), new User("John") };
public static void main(String... args) {
final Test test = new Test();
test.deleteEntry();
for (int index = 0; index < entry.length; index++) {
User user = entry[index];
if (user != null)
System.out.println(entry[index]);
}
}
public void deleteEntry() {
String SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int index = 0; index < entry.length; index++) {
if (entry[index].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[index] = null;
break;
}
}
}
private static class User {
private String name;
public User(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
}

Categories