Searching for specific value in array with while-loop - java

I have the task to build a method to search for an identical value for a variable in an array.
When there is a match, the method will return the index-Position, otherwise it should return -1.
My method works when there is a match, but I get an error when there isn´t any match.
My Code so far:
public class Schleifentest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] cherry = {7,5,6,8,9};
int magNumber = 112;
int enthalten2 = Schleifentest.sucheWhile(cherry, magNumber);
System.out.println(enthalten2);
}
public static int sucheWhile(int [] array, int a) {
int i = 0;
while(i <= array.length) {
if (array[i] == a) {
return i;
}
i++;
}
// here is the problem
return -1;
}
}
Thanks for your help.
Phil

it should be
while(i < array.length) {...}
suppose that the array has 10 elements. They are indexed from 0 to 9. When you reach the end, with your code, you'll consider the one indexed as 10, that doesn't exist, and you have the error.

Related

How check if the array is full and only add to it if it's not? [duplicate]

I've got array. I've got an isFull method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy calls.
How would you implement this?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
#Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[i] = spy; is always valid.
void isFull() should be boolean isFull(). Your implementation looks OK, just return b. full is a tricky word because technically an array is always "full". A better adjective would be populated, filled.
Since addSpy isn't filling null gaps but simply adds a spy to the end, isFull could be rewritten to return spies.length == i;.
The simplest way of doing it would be like that:
#Override
public void addSpy(AbstractSpy spy) {
if (!isFull())
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
To use that, you should change your isFull method to:
public boolean isFull() {
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
return false;
}
}
return true;
}
Keep a track of the number of filled cells of the array using a variable. And before inserting anything into it, check if the filled cells count strictly less than the size of the array (obviously you want to keep track of the array total size as well).

Recursive Search Function Java

public int search(String type) {
for (int i = 0; i < size; i++) {
if (array[size-1-i].contains(type)) return i;
}
return -1;
}
I am having trouble doing a recursive function of this previous search function , can somebody help me ?
For a recursive function, a simple solution would be to pass in the value you want to search and the index to search at as parameters to the function.
Then you check
if the index passed in is greater than length of array , then return -1 (since we were not able to find the element.
if you can find the value pass in at the index passed in, if yes, just return that index ,
if not above 2 , then try to search it at next index.
For this recursive function, start at index 0 , by passing 0 when calling the function.
Example code -
public int search(String type, int index) {
if (index >= array.length) {
return -1;
}
else if(array[index].contains(type)) {
return array.length - i + 1; # assuming size from your function is array.length
}
else {
return search(type, index + 1)
}
}
It seems you want to write a recursive variant of this search function. I am not doing any optimization in your code as you need to take care of that. I have assumed few things to make your code compile and here is the code I have tried:
static String[] array = new String[] {"John", "Sam", "David"};
static int size = array.length;
public static void main(String[] args) {
int index = searchRecursive(0,"Sam");
System.out.println("Index: " + index);
}
public static int searchRecursive(int indexToCheck, String type) {
int result = -1;
if(indexToCheck<size) {
if(array[size-1-indexToCheck].contains(type)) {
result = indexToCheck;
} else {
result = searchRecursive(indexToCheck+1,type);
}
}
return result;
}
public static int searchIterative(String type) {
for (int i = 0; i < size; i++) {
if (array[size-1-i].contains(type)) return i;
}
return -1;
}

How to find index of STRING array in Java from a given value?

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")

Java, Return true if array contains duplicate values

I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.
What is the best way to accomplish this?
public static boolean duplicates (int [] x)
I am prompting for user data like so:
public static void readData (int [] x, int i){
Scanner input = new Scanner(System.in);
System.out.println("Please enter integers, enter -999 to stop");
while (i <= 99) {
int temp = input.nextInt();
if(temp == -999){
break;
}
else {
x[i++]=temp;
}
// else
}//end while
printArray(x,i);
}//end readData
public static void printArray(int [] x, int numElementsInX){
int n = numElementsInX;
for (int i = 0; i < n; i++){
System.out.print(x[i] + " ");
}//end for
System.out.println();
}//end printArray
I am sure there is a better way to do this, but this is how I have been taught so far.
Here is a solution that:
Compiles and executes without throwing.
Uses numElementsInX as you requested.
Returns as soon as it finds a duplicate.
This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.
public static boolean duplicates (int [] x, int numElementsInX ) {
Set<Integer> set = new HashSet<Integer>();
for ( int i = 0; i < numElementsInX; ++i ) {
if ( set.contains( x[i])) {
return true;
}
else {
set.add(x[i]);
}
}
return false;
}
Here's a sample program containing the above code.
this should do it.
public boolean containsDuplicates(Integer[] x) {
return new HashSet<Integer>(Arrays.asList(x)).size() != x.length
}
You dont need numElementsInX as this is the same as x.length
edit after comment from Louis. Arrays.asList does not work with int arrays.
To convert int[] to Integer try this question How to convert int[] to Integer[] in Java?
or do soemthing like this (not tested but from memory)
Integer[] newArray = new Integer[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
This certainly isn't the most efficient way, but since you don't know about Sets yet, you can use two loops:
public static boolean duplicates (int [] x){
for (int i=0; i<numElementsInX; i++){
for (int j=i+1; j<numElementsInX; j++){
if (x[j]==x[i]) return true;
}
}
return false;
}
"set.add()" returns true if the element is not already present in the set and false otherwise. We could make use of that and get rid of "set.contains()" as in the above solution.
public static boolean duplicates (int[] x, int numElementsInX) {
Set<Integer> myset = new HashSet<>();
for (int i = 0; i < numElementsInX; i++) {
if (!myset.add(x[i])) {
return true;
}
}
return false;
}
For java, return true if the array contains a duplicate value,
boolean containsDuplicates(int[] a) {
HashSet<Integer> hs = new HashSet<>();
for(int i = 0; i<a.length; i++) {
if(!hs.add(a[i])){
return true;
}
}
return false;
}

StackOverflow Error on Java-Cannot see an infinite loop?

I am attempting to create a program which finds values which are both "triangle numbers" and "star numbers". However I am slightly confused about when the program branches to the second function etc. Any help is appreciated!
public class Recursion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count =0;
int n = 1;
int t=0;
int triangularNumber =0;
while (n<Integer.MAX_VALUE)
{
t = isTriangularNumber(n,count,triangularNumber);
triangularNumber=0;
int starNumber= ((6*n)*(n-1)) + 1;
if (starNumber ==t)
{
System.out.println(t);
}
n++;
}
if (n==Integer.MAX_VALUE)
{
System.exit(0);
}
}
public static int isTriangularNumber(int n, int count, int triangularNumber)
{
triangularNumber =triangularNumber + (n-(n-count));
if (count<=n)
{
return isTriangularNumber(n,(count++), triangularNumber);
}
else return triangularNumber;
}
}
return isTriangularNumber(n,(count++), triangularNumber);
In the above invocation, count++ is evaluated to count only. So, on every invocation, you are actually passing unchanged value of count. And hence the if condition: -
if (count<=n)
will always be evaluated to true, if it is true for the first invocation. Thus filling the stack with infinite method invocation.
Your invocation should be with ++count: -
return isTriangularNumber(n,(++count), triangularNumber);

Categories

Resources