linear search Arrays check values - java

I need to get inputs to fill an array. My problem is I also need to check if the value I input does not exist already in the array. If exists I need to show a message that says bad grade. I believe I get stuck on the search loop I and Im not able no assign the value to the array If is not already there.
String[] course = new String[9];
int index = 0;
if (menu == 1) {
boolean found = true;
do {
value = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
int pos = 0;
while (pos< course.length&& !found) {
if (value == course[index]) {
found = true;
} else {
pos++;
}
} // while
if(found == true) {
course[index] = value;
} else {
course[index]="";
}
if (course[index].equals("")) {
JOptionPane.showMessageDialog(null, "Bad Course Name");
} else{
course[index] = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
}
} while(course[index].equals("")); //last
}

The problem with your implementation is that once found is set to true, you never reset it back to false: it's a one-way street. That is why entering the first duplicate value prevents other non-duplicated values from being entered.
You can fix this by moving the declaration/initialization of found inside your do/while loop. However, a better approach would be defining a helper method that searches the array for you up to the specific position, and returns true if a duplicate is found:
private static boolean isDuplicate(String[] course, int maxIndex, String entry) {
...
}
Now the loop searching for duplicates would be hidden, along with the variable indicating the result. The code becomes more readable, too, because the name of the method tells the reader what happens inside.
Of course, you need to fix your string comparison: your code uses ==, which is not the way it is done in Java.

Related

How to iterate a condition in a while loop? Beanshell

Edited from my original post because I found a work around.
I'm trying to use a while loop to check if inputs exist. I have inputs that can vary in size, meaning I can have one input in a case or multiple in another. I'm using a while loop to execute many lines of code if the input(s) are present. The issue is that I know that I'll have at least one input in a case but in another case I may have 5,6,7, etc.
For example if I have:
input0="taco";
input1="water";
input2="sand";
With the example above in mind how do I iterate the condition of the while loop to make sure input0, input1, and input2 get executed?
In this example all of the commands within the while loop would be executed as long as input0,1,2 exist and are defined. My hope is that the integer q will scale with each input and the code within the while loop executes based on the current input.
When the loop reaches input3 I'd like it to exit the loop because that input does not exist.
I currently have the following:
int q=0;
String inputV =input(q);
while(inputV.contains("~")){ //first iteration takes "taco"
//This is where my long lines of code that need to be executed are
// I'm hoping that q will populate with 0,1,2 as the loop goes on and take "taco" "water" "sand" respectively
q++;
inputV=input(q);
//The next iteration will be input(1) = input1 which is "water"
}
New edit given the comment from Roger. The execution is having trouble getting through the if(f.equals(field)) statement. It passes through the for loop but can't process the if statement.
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
print(q + " " + inputV);
print("The input parameter is not null");
print("The input value is " + inputV);
// long lines of code executed within the while loop
q++;
inputV=input(q); }
You can find the defined variables in this.variables, global.variables or via the namespace.getVariableNames(). So with a helper method it is possible. In the example below I assumed they are defined in the global space.
input0="taco";
input1="water";
input2="sand";
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
System.out.println(q + " " + inputV);
q++;
inputV=input(q);
}
But, isn't there a better way for you to define the values such as array or list?

finding number of words present in the string in java using recursion

A class words defines a recursive function to perform string related operations. The class details
are given below:
Class name : words
Data members/instance variables
text : to store string.
w : integer variable to store total words.
Member functions/methods
words( ) : constructor to store blank to string and 0 to integer data.
void Accept( ) : to read a sentence in text. Note that the sentence may contain more
than one blank space between words.
int FindWords(int) : to count total number of words present in text using Recursive
Technique and store in ‘w’ and return.
void Result( ) : to display the original string. Print total number of words stored in
‘w’ by invoking the recursive function.
I tried this code
public static int CountWords(String str) {
int c = 0;
int i = str.indexOf(" ");
if (str.isEmpty()) {
return 0;
}else
if (i == str.indexOf(" ")) {
return c++;
}
//str.substring(0,str.indexOf(" ")-1);
c++;
return c + CountWords(str.substring(i + 1));
}
but i need to return an integer value and i am confused with that..
In your code, the last return statement is inaccessible. Reason: you have put an if-else block and have put return in both the cases. So the function actually gets returned from the if-else block itself (within else, the condition of if is always true since you assigned the very value i.e. str.indexOf(" ")).
I have written down the code according to the question you gave above...
public int findWords(int i){
if(i > text.lastIndexOf(" "))
return 1;
i = text.substring(i).indexOf(" ") + i;
if(i < 0)
return 1;
if(text.substring(i).equals(null))
return 0;
return( findWords(i+1) + 1);
}
Hope you find it well working.
Your function already is returning a integer, it just happens to always be 0.
This is due to
else if (i == str.indexOf(" ")) {
return c++;
}
Always being true and c++ only updating after the return statement was passed.
This happens because you already set i to be the indexOf(" ") and due to the implementation of incrementation using int++. Also, keep in mind hat you need to increase the number of words by 2 here, since you're ending the function between two words.
Therefore, use this instead:
else if (i == str.lastIndexOf(" ")) {
return c+2;
}
You should see that now the function is returning the correct amount of words.

Java How do i check for an arraylist object and make it true/false?

The program does one thing, depending on the users input, it removes an arraylist object and will ask you if u you want to remove another object, however, if the same object tries to be removed, i need the program to know and output 'such object does not exist', for example, 'remove "3"', then remove "3" again, the program output's "3" does not exist, the problem is that i have no idea how to implement it, what i have does not do much either. My theory is that you have to use boolean to check if the arraylist object is there in the first place, if it is: remove it, if not: output "not there".
here's what i have:
String[] id1 = { "1", "studentA" };
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(id1));
System.out.println("would you like to remove an id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc = new Scanner(System.in);
String i = sc.next();
int position = -1;
position = jim.indexOf(sc) - 1;
if (position == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(i);
}
System.out
.println("would you like to remove another id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc2 = new Scanner(System.in);
String j = sc.next();
int position2 = -1;
position2 = jim.indexOf(sc) - 1;
if (position2 == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(j);
}
If you want your program to keep on asking for user input, you need a loop, for example a while-loop, which will only terminate if the user inputs no. In addition to that, you can simply use List.remove() for removing the element, and inspect the return value (true if the item was in the list and was removed) to give the correct feedback to the user:
String[] elements = { "1", "studentA" };
ArrayList<String> list = new ArrayList<String>(Arrays.asList(elements));
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("would you like to remove an id? if so type in "
+ "the id, otherwise type: no");
String input = sc.next();
if ("no".equalsIgnoreCase(input)) {
break; // exit the loop
}
if (list.remove(input)) {
System.out.println("found and removed");
} else {
System.out.println("not found in list");
}
}
I would suggest using public boolean remove(Object o) and this will return either true or false if the element is apart of the ArrayList or not respectively. You can set some boolean variable to equal that, and use an if statement to output your desired response.
boolean contains(Object o) would check if the ArrayList contains the object, you could scan through the list and check if it is there or not. You could also use the E get(int index) to scan through and check if the strings are equal to each other using a loop.

How do you check to compare a string value to each element in an array?

So I have a String Array (sConsonantArray) and have all of the consonants stored in it.
String[] sConsonantArray = new String[] {"q","w","r","t","p","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"};
I need to check if the second last value of a word (sWord) equals a value in the array and I don't know how to call each value in the array to compare the letters other than doing sConsonantArray[5] (checking them each one at a time). I am looking for an easier way to call them, thanks for your help. Also, it doesn't appear that the (&&) operator will work, other suggestions would be appreciated.
else if (sWord.substring(sWord.length()-2,sWord.length()-1).equals(sConsonantArray I DONT KNOW WHAT TO PUT HERE)) && (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))
{
System.out.println("The plural of " + sWord + " is " + (sWord + "es"));
}
It seems to me that it would be simpler to have the consonants as a string and then use charAt:
private static final String CONSONANTS = "bcdfgh...z";
if (CONSONANTS.indexOf(word.charAt(word.length() - 2)) {
...
}
If you really want to use an array, you could change your array to be in order and then call Arrays.binarySearch. Another alternative would be to create a HashSet<String> of the consonants and use contains on that.
Try something like
else if (Arrays.asList(sConsonantArray).contains(
sWord.substring(sWord.length()-2,sWord.length()-1))
&& (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))) {
// do something
}
or Write a small Util method
public static boolean isInConstants(String yourString){
String[] sConsonantArray = new String[] {"q","w...}
for (String item : sConsonantArray) {
if (yourString.equalsIgnoreCase(item)) {
return true;
}
}
return false;
}

How to loop through an array and check for duplicates?

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.

Categories

Resources