I'm having trouble executing this function in which it would print out "true" if there is 2 consecutive numbers in an array and "false"if not. The errors I get is that a boolean cannot be converted to an int and also in the last line of code what would I have to put inside the brackets for System.out.println()?
public class A1Q2 {
private static int hasTwoLengthRun(int[] array) {
for(int i=0; i < array.length; i++){
if(array[i+1] == array[i]){
return true;
}
else{
return false;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 16, 7, 35, -2, -9, 75};
System.out.println();
}
}
1)hasTwoLengthRun() should return a boolean and not an int as you return boolean values.
2) it has a broken logic as it returns false as soon as two elements of the array are not equals between.
You should return false only when you have iterated over all elements.
3) For the compiler the method doesn't return a value since you return a value only in the for. If you have a array with no element, you don't enter in the for and you return nothing. It is not legal.
4) you will get an ArrayIndexOutOfBoundsException with the for condition as the last iteration use a index out of the array.
Here is a code that should work :
private static boolean hasTwoLengthRun(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (array[i + 1] == array[i]) {
return true;
}
}
return false;
}
I see at least 3 problems here:
Return type of hasTwoLengthRun function should be boolean
You've incorrectly arranged return false statement - it should be invocated in the end of the method
You've incorrectly used array boundaries - you'll get exception trying to reach element out of array.
Here is the corrected code:
public class Test {
private static boolean hasTwoLengthRun(int[] array) {
for(int i=0; i < array.length - 1; i++){
if(array[i+1] == array[i]){
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] array = new int[]{5, 16, 7, 35, -2, -9, 75};
System.out.println(hasTwoLengthRun(array));
}
}
You get an error, because you've written that your hasTwoLengthRun function returns int, while in your return statements you return true or false - a boolean-typed values.
Here:
private static int hasTwoLengthRun(...
says the method shall return an int. A number.
Then you return true/false. In java, those two types can not be interchanged.
So, change to:
private static boolean hasTwoLengthRun(...
Besides; your logic is wrong:
for(int i=0; i < array.length-1; i++){
if(array[i+1] == array[i]) {
return true;
}
}
return false;
is what you need instead; to A) avoid running over the length of your array and B) not returning with false when the first two elements are not matching your condition!
Related
We need to check if the first array is sorted, and if there are consecutive duplicate elements, check the second array at the index of duplicate elements. This is my code and output
The output I expect is false since a[2]=a[3] and thus we should move to the 2nd array and there b[2]>b[3].
for ex:
1.
array1[]={1,2,3,4,5};
array2[]={5,6,4,3,2};
this should return true because the first array is sorted
2.
array1[]={1,2,3,3,4};
array2[]={5,4,3,6,2};
this should also return true since array1[2]=array1[3] then we go to the array2 and there
array2[2]<array2[3] and hence it should return true.
3.
array1[]={1,2,3,3,4};
array2[]={5,4,4,4,2};
this should also return true since array1[2]=array1[3] then we go to the array2 and there
array2[2]=array2[3] and hence it should return true.
4.
array1[]={1,2,3,3,4};
array2[]={5,6,4,3,2};
this should also return false since array1[2]=array1[3] then we go to the array2 and there
array2[2]>array2[3] and hence it should return false.
In your case (4) it return true, because in your code you have if (a [i] < a[i+1]) return true inside the loop that check the duplicated values. So in array1 (1 < 2) is true, hence it return true.
How to solve this issue, you have to divide your code in two parts.
check if the first array is sorted a good explanation is in stackoverflow.com/a/19458302/3429103,
your code to complete the verification of same value successive and check in the second array.
something like
public class Main
{
public static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1])
{
return false;
}
}
return true;
}
public static boolean checkDuplicate(int[] a, int b[])
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] == a[i + 1] && b[i] > b[i + 1])
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
int array1[]={1,2,3,3,4};
int array2[]={5,6,4,3,2};
if(isSorted(array1) && checkDuplicate(array1,array2))
System.out.println("True");
else
System.out.println("False");
}
}
I am trying to solve a question in which I am given a String array of words and I have to check whether they have all same length or not. For instance if am given the array {"apple","purple","lemon"} then my method should return true, and when I am given the array {"red","blue"}, it should return false.
This is what I did so far but it is not working. I appreciate any help.
public static boolean allEqualLength(String[] myArray){
int i;
for(i=0;i<myArray.length;i++){
if(myArray[i]!=myArray[i+1])
return false;
}
return true,
}
All items having the same length is equivalent to saying all items must have the same length as the first item:
public static boolean allEqualLength(String[] myArray) {
// zero items => "all" items have same length:
if (myArray.length == 0) return true;
final int expectedLength = myArray[0].length();
for(int i = 0; i < myArray.length; ++i) {
if(myArray[i].length() != expectedLength)
return false;
}
return true,
}
But your original solution was not that far off. You just need to make sure not to exceed the array's bounds and to compare the string lengths, not the strings themselves:
public static boolean allEqualLength(String[] myArray) {
for(int i=0; i < myArray.length - 1; i++) { // -1 to not exceed bounds
if(myArray[i].length() != myArray[i+1].length()) // compare length, not memory addresses
return false;
}
return true,
}
I world do something like that:
public static boolean allEqualLength(String[] myArray) {
int strLength = myArray[0].length();
for (String str :
myArray) {
if (str.length() != strLength)
return false;
}
return true;
}
Like that you can avoid any indexing problems in your loop.
You are trying to compare the strings themselves. You should compare the length only.
myArray[i].length() != myArray[i + 1].length()
By the way, this will throw an ArrayIndexOutOfBoundsException, because you are trying to access index myArray[myArray.length]. Change the for loop to
for (int i = 0; i < myArray.length - 1; i++) {
if (myArray[i].length() != myArray[i + 1].length()) {
return false;
}
}
Also make sure you return true if the array length is 0 or 1, because the loop can't handle those.
For example you have array with length 4 , you have the positions 0,1,2,3 so in your code you run with : myArray[i]!=myArray[i+1] so on the last run you check the positions :
3 and 4 and you will get ArrayIndexOutOfBoundsException , you need to change to : length-1 on the loop condition like this :
public static boolean allEqualLength(String[] myArray){
int i;
for(i=0;i<myArray.length -1;i++){
if(myArray[i].length() != myArray[i+1].length())
return false;
}
return true,
}
If you run on myArray.length ,the positions that check :
0--1
1--2
2--3
3--4 // ERROR !!! ArrayIndexOutOfBoundsException !!
If you run on myArray.length-1 ,the positions that check :
0--1
1--2
2--3 -OK !!!
So on this way if you run the array with : myArray.length-1 , you will not get ArrayIndexOutOfBoundsException .
First things first you are not checking element lengths other issue is your for loop would try to access array index out of bounds since you have i+1, last element is already being checked that way, considering that you just need for until myArray.length - 1.
Using your code it would look something like this:
public static boolean allEqualLength(String[] myArray) {
for (int i = 0; i < myArray.length - 1; i++) {
if (myArray[i].length() != myArray[i + 1].length())
return false;
}
return true;
}
If performance is not an issue and you will not use it in 1 million strings or something, in addition to all these answers, here is an one liner:
boolean allStringsEqualLength = Stream.of(array)
.map(String::length).distinct().count() == 1;
The idea is to map each string to its length. So if distinct() stream contains only one value, that means all strings had the same length.
I am new to programming and I need some help. I am supposed to make my own method checking if one array has a subsequence to another one. Meaning if the first array is {1, 2, 3, 4, 5} and the second one is {1, 2, 3} the second one is a subsequence of the first. However if the first is {1, 2, 3, 4, 5} and the second is {1, 4, 5} it is not a subsequence, so the second has to be in order as well.
I have tried to do it this way through strings:
private static boolean subs(int[] array, int[] subsequence) {
String a = Arrays.toString(array);
String b = Arrays.toString(subsequence);
boolean c = false;
if (a.equals(b)) {
return true;
}
for (int i = 0; i < a.length(); i++) {
if (!(b.equals(a.substring(i, b.length() + i)))) {
c = false;
} else {
c = true;
break;
}
}
if (c == true) {
return true;
} else {
return false;
}
}
However I get 3 errors, here is the printscreen :
And here is how I am testing the method:
int[] fArray = { 1, 2, 3, 4, 5 };
int[] tempArray = { 2, 3, 4 };
System.out.println(subs(fArray, tempArray));
I know I probably made a lot of mistakes, so hit me with it.
Here:
for (int i = 0; i < a.length(); i++) {
if (!(b.equals(a.substring(i, b.length() + i)))) {
Your outer loop condition makes sure that i stays smaller than a.length().
But then you try to take a substring within a that goes for b.length()+i!
In other words: for any b.length() > 0 ... that code will always try to fetch characters beyond the end of a.
And there is also a bug in your result handling - it seems very much possible that you assign
c = true;
at some point; to later overwrite that with
c = false;
In other words: your code forgets that he found a match! The much easier solution: when hitting the true case, just return true there! And if you don't return within the loop; you just return false in the end.
Finally: although it seems like a cool idea to turn your arrays into strings ... that doesn't really buy you anything. You are still doing the work of going through the first array and checking if the second is in there. Writing code that does that directly on the provided arrays ... would not be much different from what you got there with your "string detour".
Edit: when using multiple returns in a method, you simply have to make sure that any possible path has a return statement. In your case:
boolean subs(... {
if equal strings
return true
for i as index in a
if a.substring equals b
return true
return false
The issue is that fArray as String has more chars than tempArray as string, so when you start to compare char by char from a to b, is a given point where the index is going beyond the size of b and then you get the exception
Your problem line is: if (!(b.equals(a.substring(i, b.length() + i))))
Why?
Lets assume your a.length() is equals 6 and b.length() is equals 2 now your looping for (int i = 0; i < a.length(); i++) with i going from 0 to 5.
Now lets say your loop executed 3 times and i is equals 4now.
Now when you call a.substring(4, b.length() + 4) with b.length() == 2 => a.substring(4, 6) but your string only goes from 0 to 5
The simplest way to do this would be to use Collections.indexOfSubList:
private static boolean subs(int[] array, int[] subsequence) {
return Collections.indexOfSubList(toList(array), toList(subsequence)) >= 0;
}
private static List<Integer> toList(int[] array) {
List<Integer> list = new ArrayList<>(array.length);
for (int num : array) {
list.add(num);
}
return list;
}
//*******************************************************************
// NOTE: please read the 'More Info' tab to the right for shortcuts.
//*******************************************************************
import java.lang.Math; // headers MUST be above the first class
import java.util.Arrays;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
int[] fArray = { 1,2,3,4,5 };
int[] tempArray = { 2,3,4 };
System.out.println(subs(fArray, tempArray));
}
private static boolean subs(int[] array, int[] subsequence) {
String a = Arrays.toString(array);
String b = Arrays.toString(subsequence);
boolean c = false;
if (a.equals(b)) {
return true;
}
String ss = b.substring(1,b.length()-1);
for (int i = 0; i < 8; i++) {
String substr =a.substring(i, ss.length()+i);
if (!(ss.equals( substr ))) {
System.out.println("heelllo");
c = false;
} else {
c = true;
break;
}
}
if (c == true) {
return true;
} else {
return false;
}
}
}
I'm trying to check wvhether my 2D array is symmetric or not. I wrote a method to check if array is symmetric. It always returns true, even if I change elements in the input array. What am I doing wrong?
Here is my code:
public class learnigBoolean
{
public static void main(String[] args)
{
int[][] array = {
{ 1, 1, 4, -1},
{ 1, 5, 0, -1},
{ 4, 0, 1, -4},
{-1, -1, 4, 10}
};
System.out.println(symetrisk(array));
}
public static boolean symetrisk(int[][] f)
{
for (int out = 0; out < f.length; out++) {
for (int in = 0; in < f[out].length; in++) {
if (f.length == f[out].length && f[out][in] == f[out][in]) {
return true;
}
}
}
return false;
}
}
if(f.length==f[out].length && f[out][in]==f[out][in])
The first check ensure your matrix is squared, the second does nothing! You are comparing each element to itself.
Don't you mean :
if(f.length==f[out].length && f[out][in]==f[in][out])
But your return statement is problematic, as stated by Michael Faisst.
You need something like this :
for (int out = 0; out < f.length; out++) {
for (int in = 0; in < f[out].length; in++) {
if (f.length != f[out].length || f[out][in] != f[in][out])) {
return false;
}
}
}
return true;
By inverting the check, you ensure that every element is checked before you return true.
Think of it this way : you only need to find one elements that doesn't satisfy the condition to say your array is not symmetric. However, you need to check every elements before you can say your array is symmetric.
You were doing the opposite, saying the array is symetric after only one check.
f[out][in] == f[out][in]
Will always return true.
Also calling "return true" will exit the loop after the first positive match which is:
f[0][0] == f[0][0]
also always true.
If you want to make it more efficient you might want to initialize your second loop to "out" to prevent checking the same pair twice, skip checking numbers against themselves and exit the loop as soon as you find a non-match like so:
public static boolean symetrisk(int[][] f)
{
for (int out = 0; out < f.length; out++) {
if (f.length == f[out].length) //only need to check this once per row.
{
for (int in = out + 1; in < f[out].length; in++)
{
if (f[out][in] != f[in][out])
{
return false; //once we find a non-matching value we stop checking
}
}
}
else
{
return false; //non-square array.
}
}
return true;
}
I am trying for too long to figure out this exersies but I am stuck here. I need to write a boolean method that will an array as argument and should return true if numbers in array are in decreasing order. Bu any time that I am trying I am having the same value or errors. Here is my code:
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i : numbers){
if(first <= i){
first = i;
return true;
}
//else{
// return false;
//}
}return false;
}
}
The problem in your code is that you cannot return true until after you went through the entire array. However, you can return false as soon as you detect an "inversion" - i.e. a situation when the number that follows the one you've seen before is greater than the prior number.
You are reasonably close to a working solution - you need to remove return true, uncomment the else, and change the final return false to return true.
To make your code more readable, rename first to prior. Also consider changing the "foreach" version of the for loop to a regular for loop that skips the initial element of the array. This would let you detect decreasing order, as opposed to non-increasing, which you currently detect.
Not sure I understand, but wouldn't this solve your issue?
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
for (int i = 0; i < numbers.Length; i++){
if (i == 0)
continue;
if (numbers[i - 1] >= numbers[i])
return false;
}
return true;
}
}
You're essentially just aiming to check that the previous item in the array isn't greater than or equal to the current item in the array, aren't you?
You initialize first with numbers[0] this causes several problems:
An empty array throws IndexOutOfBoundsException
the first check automatically passes (numbers[0] <= numbers[0])
you best check the length of numbers for 0 and use a "normal" for loop (using an index).
Your return values is also the negation of what it should be.
This might solve your issue.
public class Question{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i = 1; i < numbers.length ; i++) {
if (first <= numbers[i]) {
return false;
}
first = numbers[i];
}
return true;
}
}