Changing outputs of Arrays - java

I'm stuck on an assignment in which we have to replace every output comming from an array of "yes" with "no", and leave any other output untouched.
I keep getting the error cannot convert from String to String[], and I'm unsure of how to work around this, because I haven't been able to find any String to String[] conversion in the Javadoc.
I've been trying to find a solution for a while, so I just need a push in the right direction.
String[] makeItANegativeArray(String[] inputArray) {
String x = "no";
if (inputArray.equals("yes")) {
return x;
} else {
return inputArray;
}
}

Let's take a look at the code
//Start the function
String[] makeItANegativeArray( String [] inputArray ) {
// function needs String[] as input
// function suspects String[] as output (or return)
// initialise the variable x
String x = "no";
// if the input array is equal to the string VALUE "yes"
// (which is WEIRD because it's an ARRAY not a VALUE)
if (inputArray.equals("yes"))
{
//return A VALUE
//so here we return a VALUE while the function is suspecting an ARRAY
//this causes the error
return x;
}
else
{
//return an array
//(hence if this happens, the function terminates at the first iteration)
return inputArray;
}
}
Clearly, your input is an array and your output should be an array as well.
Hence you will have to loop over each element of the input array and construct and output array before returning anything.
For example:
String[] makeItANegativeArray( String[] inputArray ) {
String x = "yes";
String y = "no";
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i].equals("yes"))
{
inputArray[i] = y;
}
else
{
inputArray[i] = x;
}
}
return inputArray;
}
What this does is turn every "yes" in the array into a "no" and every "no" into a "yes".
So it sort of "inverts" the array.
Is this what it is supposed to do?
Alternatively,
If you just want to turn the whole array into an array of only "no's", then do the following:
String[] makeItANegativeArray( String[] inputArray ) {
String x = "no";
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i].equals("yes"))
{
inputArray[i] = x;
}
}
return inputArray;
}

NOTE: You are dealing with an array.
inputArray.equals("yes") is what causing the error. You are supposed to get each element in the Array and compare it to "yes".
What the error is telling you is you cannot compare an array of String with a String.

You should do sth like this
String [] makeItANegativeArray( String [] inputArray )
{
for(int i = 0; i < inputArray.Length; i++)
{
if (inputArray[i].equals("yes"))
{
inputArray[i] = "no";
}
}
return inputArray;
}
When you say inputArray.equals it compares array with string and it gives error.You have to iterate through all elements in array and set yes to no and return the edited array.

What are you trying to do with your String[] inputArray. Because you are comparing it's value as if it were a String object, not a String array. If you want to access the first element of the inputArray and then compare the value of that, then that would be within the makeItNegativeArray(String[]):
String[] outputArray = new String[inputArray.length];
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i].equals("yes"))
{
outputArray[i] = "no";
}
else
{
outputArray[i] = "yes"
}
}
return outputArray;
I would suggest that you have a look at the use of Arrays in Java and how they differ from single objects. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html as that may give you a real grasp of the usage of arrays and how they can be accessed. Arrays are a really important concept in programming and if you can master it, you will take another step into becoming a star.

Related

Finding the Greatest/Least value of String elements in a String array in Java

I've worked with arrays and know how to sort arrays that work with number values (double and int), but I have to make the same application using String arrays. My professor does not allow me to be "creative", or work with other static classes that might help to do the work.
I have to find the greatest value (in ASCII terms) of an array of String.
This is what I did:
public static String getGreatestValue(String[] StringArray) {
String greatestValue = StringArray[0];
for (int i = 0; i < StringArray.length; i++){
for (int index= i+1; index < StringArray.length -1; index++) {
if (StringArray[i].compareTo(StringArray[index]) == 1)
greatestValue = StringArray[i];
}
}
return greatestValue;
The list that I am working with in my Main Class looks like this:
package legacy;
public class Main {
public static void main(String[]args){
String[] names = {"D", "A", "B", "F"};
String greatestValue = StringArray.getGreatestValue(names);
System.out.println(greatestValue);
}
}
When I run the program it returns:
D
In this list the greatest value should be F.
I will be glad if someone finds a solution with this.
You don't need a nested loop. You should be comparing StringArray[i] to greatestValue (not to StringArray[index]). And you can start at 1 since you initialized greatestValue to StringArray[0]. Like,
String greatestValue = StringArray[0];
for (int i = 1; i < StringArray.length; i++){
if (StringArray[i].compareTo(greatestValue) > 0) { // <-- or < 0 as appropriate
greatestValue = StringArray[i];
}
}
return greatestValue;
Finally, please respect Java variable naming conventions (StringArray looks like a class name, variables typically start with a lower case letter).
Your problem is made because of two things. First of all you don't need nested loop. Second thing, is that you are checking if comparision is equal to 1. While you should check if it is higher or lower then 0 (depending on what you are comparing).
Here is working code:
public static String getGreatestValue(String[] StringArray) {
String greatestValue = StringArray[0];
for (int i = 0; i < StringArray.length; i++) {
System.out.println(StringArray[i]);
if (greatestValue.compareTo(StringArray[i]) < 0)
greatestValue = StringArray[i];
}
return greatestValue;
}
Here you got examples how compareTo works with String:
System.out.println("A".compareTo("B")); //prints -1
System.out.println("A".compareTo("C")); //prints -2
You're code does look a little bit too complicated. And it is recommned to begin variables with a lowercase character.
To your function, try:
public static String determineGreatest(String[] list) {
String greatest = list[0];
for (String cur: list) {
if (cur.compareTo(greatest) >= 1) greatest = list[0];
}
return greatest;
}
You can use a similar method for determining the least string.
Java 8 provides a great way to do it:
System.out.println(Arrays.stream(names).max(Comparator.naturalOrder()).get());

Sorting Strings as inserted into array in Java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}
There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.
If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.
Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

Check if every elements in array is of same value

Basically what I want to do is to check on each element in an array of int, if all elements are of the same value.
I create int array as below to pass to the method for comparing each array element, it return boolean true even tough the elements are not all the same values.
Int[] denominator = {3,3,4,3};
boolean compare;
compare = bruteforce(denominator);
public static boolean bruteforce(int[] input) {
int compare =0;
int count =0;
for (int i = 0; i < input.length; i++) {
compare = input[i];
while(count<input.length){
if(input[i+1]==compare){
return true;
}
i++;
count++;
}//end while
}//end for
return false;
}//end method
I suppose the method above will loop for and keep compare for each element of the array.
When I print out the output, it showed that it only loop once, the return the boolean as true.
I really lost the clue what could be wrong in my code.
Perhaps I just overlook of some silly mistakes.
Try,
Integer[] array = {12,12,12,12};
Set<Integer> set = new HashSet<Integer>(Arrays.asList(array));
System.out.println(set.size()==1?"Contents of Array are Same":"Contents of Array are NOT same");
Explanation:
Add the array to a set and check the size os set , if it is 1 the contents are same else not.
You only need one loop and should return false as quickly as possible where applicable (i.e. when you encounter an element that doesn't match the first).
You also need to account for the edge cases that the input array is null or has one element.
Try something like this, which I minimally adapted from the code you provided...
public class BruteForceTest {
public static boolean bruteforce(int[] input) {
// NOTE: Cover the edge cases that the input array is null or has one element.
if (input == null || input.length == 1)
return true; // NOTE: Returning true for null is debatable, but I leave that to you.
int compare = input[0]; // NOTE: Compare to the first element of the input array.
// NOTE: Check from the second element through the end of the input array.
for (int i = 1; i < input.length; i++) {
if (input[i] != compare)
return false;
}
return true;
}
public static void main(String[] args) {
int[] denominator = {3,3,4,3};
boolean compare = bruteforce(denominator);
// FORNOW: console output to see where the first check landed
System.out.print("{3,3,4,3}:\t");
if (compare)
System.out.println("Yup!");
else
System.out.println("Nope!");
// NOTE: a second array to check - that we expect to return true
int[] denominator2 = {2,2};
boolean compare2 = bruteforce(denominator2);
System.out.print("{2,2}:\t\t");
if (compare2)
System.out.println("Yup!");
else
System.out.println("Nope!");
/*
* NOTE: edge cases to account for as noted below
*/
// array with one element
int[] denominator3 = {2};
System.out.print("{2}:\t\t");
if (bruteforce(denominator3))
System.out.println("Yup!");
else
System.out.println("Nope!");
// null array
System.out.print("null:\t\t");
if (bruteforce(null))
System.out.println("Yup!");
else
System.out.println("Nope!");
}
}
...and outputs:
{3,3,4,3}: Nope!
{2,2}: Yup!
{2}: Yup!
null: Yup!
If an array elements are equal you only need to compare the first element with the rest so a better solution to your problem is the following:
public static boolean bruteforce(int[] input) {
for(int i = 1; i < input.length; i++) {
if(input[0] != input[i]) return false;
}
return true;
}
You don't need more than one loop for this trivial algorithm. hope this helps.
If all elements are the same value, why not use only one for loop to test the next value in the array? If it is not, return false.
If you want to check if all elements are of same value then you can do it in a simpler way,
int arr = {3,4,5,6};
int value = arr[0];
flag notEqual = false;
for(int i=1;i < arr.length; i++){
if(!arr[i] == value){
notEqual = true;
break;
}
}
if(notEqual){
System.out.println("All values not same");
}else{
System.out.println("All values same);
}
Right now, you are not checking if "all the elements are of the same value". You are ending the function and returning true whenever (the first time) two elements are equal to each other.
Why not set the boolean value to true and return false whenever you have two elements that are not equal to each other? That way you can keep most of what you have already.
if(input[i+1]!=compare) return false;
public class Answer {
public static void main(String[] args)
{
boolean compare = false;
int count = 0;
int[] denominator = { 3, 3, 4, 3 };
for (int i = 0; i < denominator.length; i++)
{
if(denominator[0] != denominator[i])
{
count++;
}
}
if(count > 0)
{
compare = false;
} else
{
compare = true;
}
System.out.println(compare);
}
}
One mistake that I noticed right of the bat was that you declared your array as Int[], which is not a java keyword it is in fact int[]. This code checks your array and returns false if the array possesses values that are not equal to each other. If the array possesses values that are equal to each other the program returns true.
If you're interested in testing array equality (as opposed to writing out this test yourself), then you can use Arrays.equals(theArray, theOtherArray).

Search String array for String

I want a command such as this:
setstat <statname> <level>
However, my 'statname's are in a Array; and I need to output the Array number.
This is the code I am using:
String[] statname = {"att", "def", "str", "hp",
"ranged", "pray", "magic", "cooking",
"wc", "fletch", "fish", "fm",
"craft", "smith", "mining", "herb",
"agil", "thieving", "slayer", "farming", "rc"};
int statid = statname.contains(arg[1]);
However, it doesn't work (for me). Seeing as contains(...) isn't compatible with an String[] array.
I have no idea which method to use, or how to handle this.
Use Arrays.asList(statname).indexOf(arg[1]); to find the index of an item.
Since your array is not ordered, this function will work:
public int getFoundIndex(String[] stringArr_toSearch, String str_toFind)
for(int i = 0; i < stringArr_toSearch.length; i++) {
if(stringArr_toSearch[i].equals(str_toFind)) {
return i;
}
}
return -1;
}
Call it with
int foundIdx = getFoundIndex(statName, "str");
Here's a neat code for the linear search which returns the index of the element in the array if the element is found, else returns false.
public int search(String[] array, String element)
{
if(array == null || element == null)
return -1;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(element))
return i;
}
return -1;
}
Using the approach: Arrays.asList(statname).indexOf(arg[1); can get expensive, if you have to search for the elements a lot of time.
You can sort your array once, and then do a binary search too, in order to achieve faster lookup times, if you have to search for elements in the statname array multiple times.

NullPointerException error while trying to remove a string word from an Array in a remove() method

I'm making this method remove() which takes a String word as argument, to delete from a global Array "words", but I keep getting a NullPointerException for some reason I cannot find, been stuck for hours.
Basically I check for if the word is in the first position, else if is in the last position, or else if it is in neither so I check all the array, and add the first half before the position of the word, and then add the second half after the position of the word in the array, as to skip it and "delete it". But I'm getting a NullPointerException in the for loop looking for the position of the word in the array. Code for the method is here:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
Also, if theres any suggestions for good coding practice would be appreciated, thanks!
** I can only use Arrays as my data structure for this method.
Modify the condition like this
a.equals(words[0])
because you know the string value a. But dont know what value will come from array. So even null value comes from the array it does allow the null pointer exception.
I run your code and find a few errors, I correct somethings without changing the core idea:
} else { // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
If the original array could't have null elements I would do like this:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
I would do that like this:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
I have a question for you:
Why oh why are you using an array? You should always use a collection (eg a List) unless you absolutely have to use an array (which is rare indeed).
If it were a List, you wouldn't even need this method, because List has the remove() method that does all this for you!

Categories