Trying to flip an array around but keep getting an error - java

Attempting to test and see if an array is a palindrome, however, the flipArray method I created keeps giving me trouble. The compiler gives a "not a statement" error and I'm not sure what is stopping it. The code is supposed to flip array b around, then compare array a and array b to see if they are the same:
public class Lab13_2{
public static final int SIZE = 50;
public static void main (String [] args){
Boolean palindrome = false;
String[] a = {"hello" , "goodbye", "goodbye" , "hello"};
String[] b = new String[SIZE];
b = a.clone();
palindrome = getPalindrome(a,b,a.length);
}
public static boolean getPalindrome(String[] a, String[] b, int arrayLength{
b = flipArray(b);
for(int i = 0; i <arrayLength; i++){
if(a[i] != b[i]){
return false;
}
}
return true;
}
public static String[] flipArray(String[] array){
for(int=0; i <array.length/2; i++){
int temp = array[i];
array[i] = array[array.length-1-i];
array[array.length-1-i] = temp;
}
return array;
}
}

you're missing the closing ) for the getPalindrome method.
your for loop within the flipArray method doesn't declare i before it's used within the condition or elsewhere. should be for(int i = 0; i < array.length/2; i++).
your temp variable should be of type String rather than int.
Lastly but not least you don't compare strings like this:
if(a[i] != b[i])
change it to this:
if(!a[i].equals(b[i]))

Related

Java Array Error

New to java programming and I am currently trying to create a class similar to ArrayList using Arrays.
Am trying to add elements to an array and expand the array by copying them to a new array of bigger size.
I am getting an out of index error at 20.
Code may be messy but currently really stuck.
public class MyArrayList{
private String[] strings;
private int arraySize;
private int storedStrings;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
storedStrings = 0;
for (int i = 0; i < this.arraySize;i ++){
if (strings[i] != null){
storedStrings = storedStrings +1;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
strings[i] = newArray[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize = this.arraySize +10;
}
else{
strings[storedStrings] = string;
}
for(int i = 0; i < strings.length; i++)
{
//System.out.println(strings[i]);
}
}
}
The code is being run in the test class where the error is being generated on line 10 of test class and line 47 of MyArrayList class.
This is the test code
public class TestArrayList{
public static void main(String[] args)
{
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
}
}
you can do it like this:
public void addString(String string){
if (storedStrings == this.arraySize){
this.arraySize += 10;
String[] newArray = new String[this.arraySize];
for (int i = 0; i < this.storedStrings; i++){
newArray[i] = strings[i];
}
this.strings = newArray;
}
if (strings[storedStrings] == null){
strings[storedStrings++] = string;
}
// remove this loop it will show repeating values otherwise
for(int i = 0; i < storedStrings; i++)
{
System.out.println(strings[i]);
}
}
edit: as you are new to java always think about how can you do more with less code, how to avoid repetition of code, how to merge things that do common task. That will help you write better code
edit2 : the problem is with this loop
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
if you have 50 elements in array the getString method on (eg) i = 25 will be 25*5 = 125 which is not the index in the array that's why you are getting ArrayIndexOutOfBound Exception.
you can add
public int size(){
return storedStrings;
}
to check the size of your list which is the maximum item that is inside the list
First with your code there is a mistake in this line
strings[i] = newArray[i];
because you arenĀ“t copying the old data to new array but cleaning the strings array, I suppose that you wish do the contrary action.
In other hand you have extra code that you could improve.
public class MyArrayList{
private String[] strings;
private int arraySize;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
// Since you always do this
// it's better to use a local variale
int storedStrings = 0;
// Use the foreach syntax
// it's less prone to errors
// and easier to read
for (String s : this.strings){
if (s != null){
storedStrings++;
}else{
// since you want to count the strings in your array
// and you put them in this array
// one after the other
// no need to check the whole array
// when you find null you can exit the loop
break;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
// here we need to copy the content of strings in newArray
// NOT the other way
newArray[i] = this.strings[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize += 10;
}else{
this.strings[storedStrings] = string;
}
}
public String[] getStrings(){
return this.strings;
}
}
As for the test class
public static void main(String[] args){
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (String s : a.getStrings()){
System.out.println(a);
}
}

StringIndex OutOf Bounds Exception

i am trying to find out the number of characters that exist in every string in an array
so i write this code . it doesn't work and getting error in the line
char c = a.charAt(0);
it seems that there is an empty string passing to the method so it throws this exception but i don't know how to fix that and make the code work
what should i do to fix it?
this is the code:
public class Gem_Stones {
public static int counter = 0;
public static int result = 0;
public static void main(String [] args){
Scanner c = new Scanner(System.in);
int N = Integer.parseInt(c.nextLine());
String [] Gem = new String[N];
for(int i =0; i<N ; i++){
Gem[i] = c.nextLine();
}
solv(Gem[0] , subArr(Gem));
System.out.println(result);
}
public static String [] subArr(String [] input){
String [] ans = new String[input.length - 1];
for(int i =0 ; i<ans.length ; i++){
ans[i] = input[i+1];
}return ans;
}
public static void solv(String a , String [] str){
char c = a.charAt(0);
for(int i = 0 ; i<str.length ; i++){
if(contain(c , str[i]))
counter++;
}
if(counter == str.length){
result++;
solv(sub(a) , str);
} else {
solv(sub(a) , str);
}
}
public static String sub(String input){
StringBuilder sb = new StringBuilder(input);
sb = sb.deleteCharAt(0);
String result = sb.toString();
return result;
}
public static boolean contain(char c , String s){
for(int i=0 ; i<s.length(); i++){
if(s.charAt(i) == c)
return true;
}return false;
}
}
you need to check if the string is empty before you make any operation (and also to check if is null)
if(a == null || a.equals("") ){
return null; //or throws an exception or -1 or anything you want to do when a is empty
}
char c = a.charAt(0);
Check the string for isEmpty() befor charAt(0), just return if true.
If all you are doing is trying to find out the number of characters that exist in every string in an array, then you are doing a lot of unnecessary steps such as deleting characters.
Consider using a nested for loop:
public static int solve (String[] strings, char target) {
int count = 0;
for (String s : strings) {
for (int i = 0; i < s.length(); i++) {
if (target == s.charAt(i)) {
count++;
}
}
}
return count;
}

Changing outputs of Arrays

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.

Java method argument in calling and caller methods

Just simple reverse string method.
FYI, correct methods are reverseString1 and reverseString2,
but revereStirng3() doesn't give me correct output.
I think this is because of method args and return values are stored in the Stack and related with this concept. But I don't clearly understand why revereStirng3() doesn't work correctly.
Please let me know whey this is not working.
This is what I understand, and please correct me if I'm wrong.
1. main() calls revereStirng3(A) where this passing argument array A is stored in the stack frame for the main().
revereStirng3(char[] A) where this passed argument array A is stored in revereStirng3's method frame which means main's A[] is copied to revereStirng3's stack frame's method argument A[].
After reverse, revereStirng3 creates new String(A) for return String.
Then, I thought, in the main, returned new String(A) is correctly print reversed string, but actually not.
// Given a string "abcdef", reverse it. so output should be "fedcba"
import java.util.*;
public class ReverseString {
static String revereStirng3(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return new String(A);
}
static void revereStirng1(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
}
static String revereStirng2(String str) {
char[] A = str.toCharArray();
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return String.valueOf(A);
}
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.print( revereStirng3(A) + "\n" ); **// print out "abcdef"**
System.out.println( "" );
revereStirng1(A); // print out "fedcba"
for(int i=0; i<A.length; i++)
System.out.print( A[i] );
System.out.println( "" );
System.out.print( revereStirng2(s) + "\n" ); // print out "fedcba"
System.out.println( "" );
}
}
Ok, given that zenbeni has got the real results, here is what is happening.
An array in Java is an object, so in revereString1 and revereString3 you get a copy of the reference to the array. So, your changes modify the original array, which (after the first method execution) has been reversed. Of course, the second execution reverses it again, so you get the reverse of the reverse, which is the original String.
Try using a new, locally defined array to create the reversed String and everything will work fine.
From apache commons:
StringUtil.reverse(str);
I have copied your method and executed it
System.out.println(revereStirng3("abcdef".toCharArray()));
on the result was
fedcba.
The problem is located in the main function:
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.println( revereStirng3(A)); // print out "abcdef"**
revereStirng1(A);
System.out.print(Arrays.toString(A)); // print out "fedcba"
System.out.println(revereStirng2(s)); // print out "fedcba"
}
Your comments do not show the true.
The valid output for it would be
fedcba
[a,b,c,d,e,f]
fedcba
And this is because you operate on the same array for three test cases. In the second step you pass allready reversed array as input. This results that the order has not changed.

Returning the element number of the longest string in an array

I'm trying to get the longest method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part.
public static void main(String [] args)
{
Scanner inp = new Scanner( System.in );
String [] responseArr= new String[4];
for (int i=0; i<4; i++)
{
System.out.println("Enter string "+(i+1));
responseArr[i] = inp.nextLine();
}
int highest=longestS(responseArr);
}
public static int longestS(String[] values)
{
int largest=0
for( int i = 1; i < values.length; i++ )
{
if ( ????? )
}
return largest;
}
for (int i = 0; i < values.length; i++)
{
if (values[i].length() > largest)
{
largest = values[i].length();
index = i;
}
}
return index;
Note: initialize the int i with 0 - array index is 0-based.
Back in your main, you could then do System.out.println("Longest: " + responseArr[highest]); etc.
Here's how I'd write it:
public static int findIndexOfLongestString(String[] values)
{
int index = -1;
if ((values != null) && (values.length > 0))
{
index = 0;
String longest = values[0];
for (int i = 1; i < values.length; ++i)
{
if (values[i].length() > longest.length())
{
longest = values[i];
index = i;
}
}
}
return index;
}
You will want to store two things in your longestS method: the largest length so far, and the array index of the largest length. Also keep in mind that array indices start at 0 in Java. A for loop initialised with int i = 1 is actually going to start at the second index.
My solution:
public class JavaApplication3
{
public static void main(String[] args)
{
String[] big={"one","two","three"};
String bigstring=null;
int maxlength=0;
for(String max:big)
{
if(maxlength<max.length())
{
maxlength=max.length();
bigstring=max;
}
}
System.out.println(bigstring);
}
}

Categories