I have an array like this :
String[] array = { "Designation1", "Designation2", "Designation3" };
If user put "Designation2" as input then the code should return 1.
It may be very simple question, but I am very new in Java. So please give some suggestions.
Consider using List instead of array (of just wrap your array in List). This way you will have access to method like indexOf(element) which will return index of first founded element, of -1 if no element in array was found.
String[] array = { "Designation1", "Designation2", "Designation3" };
List<String> list = Arrays.asList(array);
System.out.println(list.indexOf("Designation2")); //prints 1
System.out.println(list.indexOf("foo")); //prints -1
You can loop over the Strings in the array and find the index for which the String matches what you are looking for.
int index = -1;
for (int i=0; i<array.length;i++) {
if (array[i].equals(value)) {
index = i;
break;
}
}
You could just use a for loop
String[] array = { "Designation1", "Designation2", "Designation3" };
Scanner kb=new Scanner(System.in);
String input=kb.next();
int index;
for(int i=0;i<array.length;i++)
{
if(array[i].equalsIgnoreCase(input))
index=i;
}
You can do it like this.
String userinput="Designation2";
String[] array = { "Designation1", "Designation2", "Designation3" };
int length=array.length();
int index=0;
for(int i=0;i<length;i++)
{
if(array[i].equals(userinput))
{
index=i;
break;
}
}
And index will give you the array key that user wants.
Regards..
There are no direct search method for array so you need to convert it to list first
String[] array = { "Designation1", "Designation2", "Designation3" };
assert Arrays.asList(array).indexOf("Designation2") == 1;
assert Arrays.asList(array).indexOf("Anything else") == -1;
Do not forget that -1 mean 'not found'
Or you can sort it and use binarySearch
You can use ArrayUtils from Apache Commons.
String[] array = { "Designation1", "Designation2", "Designation3" };
System.out.println(ArrayUtils.indexOf(array, "Designation1"));//0
System.out.println(ArrayUtils.indexOf(array, "Designation2"));//1
System.out.println(ArrayUtils.indexOf(array, "Designation3"));//2
In order to do this task, you can use two arrays, one for key names and ones for their values. Simply search for the key in the first array, get the index of the key name and use it to get the value from the second array. It's not the most efficient, and this is probably not the best answer, but it works for me.
Just make sure the indexes in the arrays line up, for example:
{"my","three","keys"};
{"My","Three","Values"};
In this case, the key/value setup would be;
my/My
three/Three
keys/Values
In your case, you don't need to use the value array, just use the index.
Also try using ArrayList instead of arrays, as you can use ArrayList.indexOf(key) to get the index of key in the ArrayList.
Hope this helps you and others with this problem. ☺
Related
What i am trying to achieve is, let's say I've these variables below:
String num1 = "blah1";
String num2 = "blah2";
String num3 = "blah3";
String num4 = "blah4";
String num5 = "blah5";
Now i want to create a single string variable which would iterate the all values of string's variable inside loop.
for(int i=0; i<=5; i++){
System.out.println(num+""+i); //I know, this would give me some errors. But i want to make something like this to call all string variables.
}
Here i want to print all the values of string's variable by using loop, How to achieve this?
Help would be appreciated!
This is a use case for an array:
String nums[] = new String[] {
"blah1",
"blah2",
"blah3",
"blah4",
"blah5"
}
And then you can easily iterate through the values (note that you don't need to duplicate the number of elements (5) ):
for(int i=0; i<nums.length; i++) {
System.out.println(nums[i]);
}
More about arrays in the Oracle tutorial.
Alternatively, you may use a List instead of an array.
What you need is an Array - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An Array is a container containing a fixed number of values that are the same type, eg:
String [] nums = new String[5];
The above line creates a array called nums of type String which can hold 5 individual String values (they are initially null).
Another way to declare this would be to use:
String [] alt_nums = {"blah1","blah2","blah3","blah4","blah5"};
This set's each value stored in alt_nums to a specific value as declared in the curly braces.
To iterate through an Array you can use an iterative for loop
for(int i = 0; i < alt_nums.length; i++) {
System.out.println(alt_nums[i]);
}
or you can use an enhanced for loop which does this automatically.
for(String num : alt_nums) {
System.out.println(num);
}
You can also use java 8:
List<String> strings = Arrays.asList("sad", "asdf");
strings.forEach(str -> System.out.println(str));
I want to find the index of the start up letter and then show the index of that item in array or array list in java.
Example: I have:
String[] arr={"apple","at","book","bad","car","cat"};
when I input a: then i will get index =0, b: i will get index=2, c: i will get index=4
Because my array item is over 20,000 , so using linear Search is too slow.
and my list is unsorted, so i can't use Binary Search also.
I want to get index of the item like the example above, what can i solve with this?
You can run some initialization code (before the user starts to type letters in).
// initialize an array that has a cell for each letter with value -1
int[] firstIndexes = new int[26];
for(int i=0;i<firstIndexes.length;i++) {
firstIndexes[i] = -1;
}
// loop over original array and look for each letter's first occurence
for(int i=0;i<wordsArray.length;i++) {
char c=wordsArray[i][0];
if(firstIndexes[c-'a'] < 0) {
firstIndexes[c-'a'] = i;
}
}
Then when the user types a letter you just need to find its index in the 'firstIndexes' array.
If you want to get all the indexes of words starting with a certain letter then try this one:
While adding the Words to your Array/list (that will hold all your words) you could also add it to a map that will hold all indexes for every first letters.
Map<String, ArrayList<Integer>> myMap = new HashMap<String, ArrayList<Integer>>();
public void yourmethod() {
//adding all your words to an Array/arraylist goes here. (arr[] in this case)
string firstLetter = yourword.substring(0,1);
if(myMap.constainsKey(firstLetter)) {
myMap.get(letter).add(yourword);
} else {
myMap.put(firstLetter, yourword);
}
}
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
I have a String array like,
String[] abc= new String[]{};
and my List has some values. I iterate the list and add each list element to string array.
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}
errList.size() has 6 values. But when the for loops executed I get java.lang.ArrayIndexOutOfBoundsException. Any inputs?
You're creating a String[] object of zero length; so, when you try to assign an item to abc[i], it is accessing an index not within your bounds 0 <= i < 0.
You should allocate abc with a length instead:
String[] abc= new String[errList.size()];
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}
You need to craete the string array with the same size as the list. It is not dynamic. Perhaps you can tell what you are trying to achieve with this exercise.
Did you try to use for each loop which is widely used in collection framework?
String[] abc = errList.toArray(new String[0]);
Or:
String[] abc = new String[errList.size()];
errList.toArray(abc);
I would just do this
String[] abc= errList.toArray(new String[errList.size()]);
App reads TextEdit value to String and then converts to ArrayList. But before converting it removes spaces between words in TextEdit. So after converting I get ArrayList size only 1.
So my question is how to get the real size. I am using ArrayList because of its swap() function.
outputStream.setText("");
stream = inputStream.getText().toString().replace(" ", "");
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = Arrays.asList(stream);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
}
stream = inputStream.getText().toString();
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = new ArrayList<String>();
for (String x : stream.split(" ")) arrayList.add(x);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
That is my guess at what you actually wanted to do...
The size and the length are different things.
You try to get the size when you want the length.
Use arrayList[0].length() instead of your arrayList.size().
If you want to parse your String to an Array try:
List<String> arrayList = Arrays.asList(stream.split(","));
(this example expects that your text is a comma separated list)
Arrays.asList() expect an array as paramter not just a String. A String is like an array of String of size 1 thats why your list is always of size 1. If you want to Store the words of your String use :
Arrays.asList(stream.split(" ")); //Don't use replace method anymore