Obtaining index from the Joptionpane [duplicate] - java

This question already has answers here:
How to select an index value from a String Array in a JOptionPane
(2 answers)
Closed 8 years ago.
I want to access the index of the option selected by the user.Eg, in the figure below,if i choose microsoft option then it should give me the index 1.Is this possible?

Well you get "Microsoft" (well the Object showing Microsoft at least) as the return value from the show call, is that good enough?
If you need the index just find the index of that return value in the input array you provided to the dialog.
See the input section of the java tutorial:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#input
Assuming you are using showInputDialog(..):
Object[] possibilities = {"Broadcom...", "Microsoft"};
Object result = JOptionPane.showInputDialog( frame, "Capture Interfaces", "Input", JOptionPane.PLAIN_MESSAGE, icon, possibilities, possibilities[0]);
if (result != null) {
//result is the choosen object, if you need the index even so:
int index = 0;
for (Object o : possibilities) {
if (result == o)
break;
index++
}
//index is now the index...
}

Related

Removing an array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 4 years ago.
Got a simple auction program running, only problem is that if a user is removed before auction is closed his/hers bids are supposed to be removed. I dont have it 100% down yet but I think I am on the right path.
The bids have to be arrays and right now it is kinda removed or just moved maybe. This was a the error earlier.
Top Bid:[Wow 400 kr, Boy 311 kr, Man 33 kr, Dude 2 kr]
command>remove user
Name>wow
Wow has been removed from registry
command>list auctions
Auction # 1: Item. Top Bid:[Boy 311 kr, Man 33 kr, Exception in thread "main" java.lang.NullPointerException
public void removeBid(String name) {
for(int a = 0;a < bidIndex; a++) {
if(bids[a].getUser().getName().equals(name)) {
bids[a]=null;
bidIndex--;
break;
}
}
sortBids();
public void sortBids() {
if(bidIndex > 1) {
for(int a = 0; a < bidIndex -1; a++) {
for(int b = a + 1; b < bidIndex; b++) {
if(bids[a] == null || bids[a].getBid() < bids[b].getBid()) {
Bid temp = bids[a];
bids[a] = bids[b];
bids[b] = temp;
}
}
Arrays cannot change size once initialized. If you create an array new String[10]; it will forever have 10 items (which are null by default). Setting an index to null doesn't change this.
String[] items = new String[] {"String1", "String2", "String3"};
items[1] = null;
This arrays would now look like [String1, null, String3].
If you need to change arrays as much as it seems, you're better off using a List or Map.
I would suggest using a HashMap if you want to easily link one object to another. In this case it looks like you'd be linking a String (name) to the Bid object.
Map<String, Bid> bids = new HashMap<String, Bid>();
Bid bid1 = new Bid(/*...*/);
Bid bid2 = new Bid(/*...*/);
// Add bids to the map
bids.put("Wow", bid1);
bids.put("Boy", bid2);
// Get any of these objects
Bid retrievedBid = bids.get("Wow");
// Or remove them
bids.remove("Wow");
HashMaps are similar in concept to associative arrays from other languages, where you have a key -> value relationship. Each key is unique, but the value can repeat.
They can also be converted to arrays if the final result you need is an array.
Bid[] bidsArray = new Bid[0];
bidsArray = bids.values().toArray(bidsArray);
One way you can achieve this is to convert the array to a list and then remove the bid using Java streams and convert back.
List<Bid> bidsList = Arrays.asList(bids);
bidsList = bidsList.stream()
.filter(n -> !n.getUser().getName().equals(name))
.collect(Collectors.toList());
bids = bidsList.toArray(new Bid[bidsList.size()]);

Error message being thrown: Index out of bounds exception [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
For the following code I am getting an index out of bounds exception and I am not sure as to why. Any help is greatly appreciated.
public Rabbit nearestRabbit()
{
List<Rabbit> rabbits = this.getWorld().getObjects(Rabbit.class);
if (this.getWorld().getObjects(Rabbit.class) == null)
{
return null;
}
Rabbit nearest = rabbits.get(0);
double distance = distanceTo(nearest);
for (Rabbit rabbit : rabbits)
{
double thisDistance = distanceTo(rabbit);
if (thisDistance > distance)
{
distance = thisDistance;
nearest = rabbit;
}
}
return nearest; //#######
}
This is mainly due to your list size, I know that you have checked null for the list but since the list is not null it can still be empty with the size 0 and you can not access to the element at index 0.
I recommend you to check the list size.
You are getting this exception by not checking if the index is in bounds in the call rabbits.get(0).
A simple workaround is to put this code first.
if (rabbits.isEmpty())
return null;
This checks if the list is empty before making any other calls.
Also, it would be best to refrain from reference this.getWorld().getObjects(Rabbit.class) more than once, especially after holding it as a variable which is much more accessible.
Add a size check to your if
if (this.getWorld().getObjects(Rabbit.class) == null || rabbits.isEmpty() )
A list may well not be null yet still be empty. E.g. any freshly generated one:
LinkedList<Object> objs = new LinkedList<>();
System.out.println(objs != null && objs.isEmpty()); //true
Your IndexOutOfBound is probably when you are getting element at index 0 where the list might be empty.
if (!rabbits.isEmpty())
{
Rabbit nearest = rabbits.get(0);
}

how to add explicit wait in drop down in selenium which is dependent on another Dropdown list? [duplicate]

This question already has answers here:
how to add explicit wait in drop down in selenium which is dependent on another dropdown?
(3 answers)
Closed 6 years ago.
how to add explicit wait in drop down using selenium until it finds the text ?
below code will wait until specified text is not present..
int i=0;
while(i==0)
{
try{
Select select = new Select(driver.findElement(By.xpath("ELEMENT_XPATH")));
select.getOptions().indexOf(0);
int ed = select.getOptions().indexOf(0);
if(ed==0); //check whether it's got your index or not(if not then it will throw error and go to Catch section)
{
System.out.println("Pass got.. Index Value");
}
i=1; //if it got your index value in drop down then .. exit from loop..
}catch(org.openqa.selenium.NoSuchElementException NSEE)
{
i=0; // iteration will continue until .. you'll not get your index in Drop down..
}
}

JCombobox and String.equals(null) [duplicate]

This question already has answers here:
How to check if my string is equal to null?
(28 answers)
Closed 8 years ago.
Here is my code :
if (ChoixPortCom.equals(null) == true ) JOptionPane.showMessageDialog(null, "Choose Port COM");
and I get the famous java.lang.NullPointerException
My JCombobox is filled like :
1st -> nothin/empty null no String nothing
2nd -> COM1
3nd -> COM2
....
Why is "if" condition not right ?
choixPortCom.equals(null) will never be true. If choixPortCom is not null, then the expression will return false as expected. If choixPortCom is null, then the expression will throw a NullPointerException, since you are attempting to call a method on null; this is what's happening in your case. The appropriate way to check for null is:
if (choixPortCom == null) // I've assumed a more common naming convention
There is also an Objects class in Java 7 that has some useful methods for null-checking. For example, Objects.requireNonNull():
Objects.requireNonNull(choixPortCom, "input can't be null!")
It should be
if (ChoixPortCom == null)
Now if ChoixPortCom is null it will throw a NullPointer because you are trying to invoke a method (equals) on a null reference.
And something I like to think of as a best practice is to always use brackets:
if (ChoixPortCom == null) {
JOptionPane.showMessageDialog(null, "Choose Port COM");
}

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

Categories

Resources