Array needle in haystack - java

I have an assignment to create an int array that is serched in another method for a user input int value then displays the index of that element in the array. I have that part working just fine and I personaly chose to make the elements in the array random values from 1 - 10.I also need to have the program display a message ("Element not found in array") in the event that the given number isn't in the array. I cannot seem to get this part to work correctly and am hoping I can get some advice here.
import java.util.Scanner;
public class NeedleInHaystack {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int[] haystack = new int[10];
System.out.println("The array being used is: ");
for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}
returnIndex(haystack, needle);
}
public static int returnIndex(int[] haystack, int needle) {
int index = needle;
System.out.println("\nThe needle is found at index: ");
for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}
return index;
}
}
The program is an int needle in a hastack array. What is the best way to make the program end "gracefully" in the event that the input value is not present in the random array?
The assignment was worded as follows:
"Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle"."

Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle
So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle
public static int returnIndex(int[] haystack, int needle) {
int index;
System.out.println("\nThe needle is found at index: ");
for (index = 0; index < haystack.length; index++) {
if (haystack[index] == needle) {
System.out.println("value found at index"+index);
return index;
}
}
System.out.println("The value not found in array");
return needle;;
}

You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.
public static int returnIndex(int[] haystack, int needle) {
boolean found = false;
int index = needle;
System.out.println("\nThe needle is found at index: ");
for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
found = true;
}
}
if (found) return index;
else {
System.out.println("Not found.");
return null;
}
}
}

Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.
But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.
public static int returnIndex(int[] haystack, int needle) {
System.out.println("\nThe needle is found at index: ");
for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == needle) {
System.out.println(i);
return i;
}
}
throw new NoSuchElementException(„Element not found in array“);
}

Related

Finding Spaces In A String Using indexOf in Java

So I am trying to write a Method that will return to me the number of occurrences of a String in Another String. In this case it's finding the number of spaces in a String. It's as if indexOf() is not recognizing the spaces.
Here is my Method:
public int getNumberCardsDealt()
{
int count = 0;
int len2 = dealtCards.length();
int foundIndex = " ".indexOf(dealtCards);
if (foundIndex != -1)
{
count++;
foundIndex = " ".indexOf(dealtCards, foundIndex + len2);
}
return count;
}
Here is my application:
public class TestDeck
{
public static void main(String [] args)
{
Deck deck1 = new Deck();
int cards = 52;
for(int i = 0; i <= cards; i++)
{
Card card1 = deck1.deal();
Card card2 = deck1.deal();
}
System.out.println(deck1.cardsDealtList());
System.out.println(deck1.getNumberCardsDealt());
}
}
Note that I already have a Card Class and the deal method works.
Check the documentation of the indexOf method. You are using it wrong.
You should change the invocation
" ".indexOf(dealtCards);
To
dealtCards.indexOf(" ");
That is, invoking the method on the concerned string and passing to it the character you are looking for, not the other way around.
Moreover, your method would not calculate it correctly anyway, you should change it to something like:
public int getNumberCardsDealt() {
int count = 0;
int foundIndex = -1; // prevent missing the first space if the string starts by a space, as fixed below (in comments) by Andy Turner
while ((foundIndex = dealtCards.indexOf(" ", foundIndex + 1)) != -1) {
count++;
}
return count;
}
#A.DiMatteo's answer gives you the reason why your indexOf doesn't work currently.
Internally, String.indexOf is basically just iterating through the characters. If you're always just looking for a single character, you can trivially do this iteration yourself to do the counting:
int count = 0;
for (int i = 0; i < dealtCards.length(); ++i) {
if (dealtCards.charAt(i) == ' ') {
++count;
}
}

Java OOP-Accessing the last element in an array of objects

I am practicing object orientation here entering in basketball player names and how many points scored and rebounds grabbed.
How would I go through each element in an array of objects to find the last player with an even amount of points?
This is the code I have so far to enter the information. What do I need to do in my second forloop to examine each element and then display the last element that fits my criteria?
class basketballObj
{
public static void main (String[]args)
{
Basketball bbArray[];
String theName;
int thePoints;
int theRebounds;
int index;
int noOfElements = 0;
bbArray = new Basketball[3];
for(index = 0; index < bbArray.length; index++)
{
System.out.println("Enter a name ");
theName = EasyIn.getString();
System.out.println("Enter points scored ");
thePoints = EasyIn.getInt();
System.out.println("Enter rebounds grabbed ");
theRebounds = EasyIn.getInt();
bbArray[index] = new Basketball(theName, thePoints, theRebounds);
noOfElements++;
}
for(index = 0; index < bbArray.length; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
}
}
}
}
Well if you want to find the last player with an even amount of points, you don't actually want to go through each element ;-). Try:
for(index = bbArray.length-1; index >= 0; index--)
{
if(bbArray[index].getPoints() % 2 == 0)
{
//add whatever relevant code here.
break; //this line breaks the for loop (because you've found a player with an even amount of score
}
}
we start at bbArray.length-1 because while you array contains 3 elements, arrays are zero-indexed. Meaning that to get the first element, you will have to call bbArray[0]. Similarly call bbArray[2] for the last element.
Simple. Iterated your array backwards.
boolean found = false;
for(int index=array.length-1; index>-1 && !found; index--) {
if(array[index].getPoints()%2 == 0) {
// found element. Break out of for loop
found=true;
}
}
You've pretty much got it.
Create a temporary, uninitialized variable Basketball temp; before the for loop that iterates through the bbArray and then set it equal to the bbArray[index] if the if condition is met.
If you want to save the index it was found at then create an int indexFound; as well.
Looping through it backwards as user2651804 suggested yields this:
public class basketballObj
{
public static void main(String[] args)
{
...
Basketball temp;
int indexFound = -1;
...
for(index = bbArray.length - 1; index >= 0; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
temp = bbArray[index];
indexFound = index;
break;
}
}
//note temp will be null if no scores were even
//if (temp != null)
//you can use the above if statement if you don't want to use indexFound
//you can also just check if indexFound == -1
if (indexFound != -1)
{
System.out.println("Found at index: " + indexFound);
//
}
}
}

Find longest strings

I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}

Palindrome Program

I'm trying to write a program which will output what Palindromes will work from entering in a string and how many there are. I keep getting a lot of errors and I'm still trying to get my head around some of the harder topics in Java!
Here's what I have already, as always, all answers are greatly appreciated!
public static boolean Palindrome(String text) {
int index;
int palindrome;
System.out.println("Please enter your text ");
text = EasyIn.getString();
for(index = 0; index < amount.length() / 2; index++) {
if(text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
System.out.println("The number of valid palindrome(s) is " + amount);
amount = EasyIn.getString();
}
I think the problem is in amount.length(), you should use text.length(), since you are looping over the half of text. The algorithm works fine. Here is a reduced example:
public static boolean palindrome(String text)
{
for (int index = 0; index < text.length() / 2; index++) {
if (text.charAt(index) != text.charAt(text.length() - index - 1)) {
return false;
}
}
return true;
}
Note:
You forgot to add a return true statement, if you don't add one, is possible that the for loop finishes and no return statement is reached, which will cause an error.
I would recommend you to follow Java naming conventions. You method should be called like someMethodName instead of SomeMethodName. This last is used for class names.
Edit:
As #bobbel commented, you could improve this code by assigning text.length() to a variable and using it inside the for.
There can be two things:
ammount variable that you used either it could be a string array that you are maintaining strings inside it, if this is the case than you have to loop first through array of strings and then maintain one nested loop to check that strings inside it are palindrom or not
or second case is that you have used the variable incorrect it may be text instead of ammount
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter string to check for palidrome");
String orginal = in.next();
int start = 0;
int middle = orginal.length()/2;
int end = orginal.length() - 1;
int i;
for(i=start; i<=middle; i++) {
if(orginal.charAt(start) == orginal.charAt(end)) {
start++;
end--;
} else {
break;
}
}
if(i == middle+1) {
System.out.println("palidrome");
} else {
System.out.println("not palidrome");
}
}
This is the Simplest way of Checking Palindrom number.
package testapi;
public class PalindromNumber {
public static void checkPalindrom(Object number) {
StringBuilder strNumber = new StringBuilder(number.toString());
String reverseNumber = strNumber.reverse().toString();
if (number.toString().equals(reverseNumber)) {
System.out.println(number + " is palindrom number");
} else {
System.out.println(number + " is not palindrom number");
}
}
public static void main(String[] args) {
checkPalindrom(101);
checkPalindrom(10.01);
checkPalindrom("aanaa");
}
}

Sequence Count i.e suppose aabbbaaccd is string output should be a=2,b=3,a=2,c=2,d=1

As i have tried ,it gives ArrayIndexOutOfBounds Ecxeption and does not print last char
please help me to find bug in my code.or is there any alternate
public static void sequenceCount(String s) {
int counter;
int i=0;
char c;
char[] arr = s.toCharArray();
while(i<arr.length){
counter=0;
c = arr[i];
while(c==arr[i]){
counter++;
i++;
}
System.out.println("letter"+" "+c+":"+"number of times"+counter);
}
}
As i am a novice to java my code may be inefficient
Your inner loop is not bound by the length of the array. Try:
while(i < arr.length && c==arr[i]){
counter++;
i++;
}
This works - you need to ensure that your inner loop doesn't pass beyond the end of the string, and you need to always catch the last letter, too:
public static void sequenceCount(String s) {
char[] arr = s.toCharArray();
int i = 0, n = arr.length;
while (i < n) {
char c = arr[i];
int count = 0;
do {
++i; ++count;
} while (i < n && arr[i] == c);
System.out.println("letter "+ c +":"+"number of times " + count);
}
}
My approach would be to use two for loops.
The first for loop would run a loop with the decimal equivalent of A to Z.
The second for loop would run a loop that runs through the entire character array/string (I'd prefer a string rather than a char array here) and check to see if that given value at that index is equal the the value ran by the first for loop. If they are equal than add one to count. Print.
Don't forget to reset your counter after every run as well.
Similar Topic can be found here: Counting letters in a string using two for-loops
While many answers here are O(n^2), I tried to do it within O(n) time using recursion. This is modified from existing code that I already had so I know the method returns an int, but I don't use it (it's left over from copied code - fix it as you see fit)
public class CountCharSeqRecursive {
private String test = "AAABBA"; // (3)A(2)B(1)A
private StringBuilder runningString = new StringBuilder();
public static void main(String[] args) {
CountCharSeqRecursive t = new CountCharSeqRecursive();
System.out.println(t.getEncryptedValue(t.test));
}
public String getEncryptedValue(String seq){
int startIndex=0;
this.createCounterSeq(seq.charAt(startIndex), seq, startIndex);
return runningString.toString();
}
private int createCounterSeq(char prev, String sequence, int currentIndex){
return createCounterSeq(prev, sequence, currentIndex, 0);
}
private int createCounterSeq(char prev, String sequence, int currentIndex, int count){
if(currentIndex<sequence.length()){
char current = sequence.charAt(currentIndex);
if((prev^current) < 1){
++count;
}else {
this.addToSequence(count, prev);
count = 1;
}
return count += createCounterSeq(current, sequence, ++currentIndex, count);
}
this.addToSequence(count, prev);
return count;
}
private void addToSequence(int count, char ch){
runningString.append("("+count+")").append(ch);
}
}
My solution using HashSet, Works for all cases of a non-empty string.
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Character> set = new HashSet<Character>();
String input = "aabbcdeaab";
set.add(input.charAt(0));
int count = 1;
StringBuilder output = new StringBuilder("");
for(int i=1;i<input.length();i++) {
char next = input.charAt(i);
if(set.contains(next)) {
count++;
}else {
char prev = input.charAt(i-1);
output.append(Character.toString(prev) + count );
set.remove(prev);
set.add(next);
count=1;
}
}
output.append(Character.toString(input.charAt(input.length()-1)) + count );
System.out.println(output.toString());
}

Categories

Resources