How to print out the index of a boolean array? - java

I'm trying to get all of the indexes of a Boolean array to be printed out where its element is true. The end goal is to be able to find a prime number of the indexes (where I change each index number that isn't prime to false in the array) then print out only what is left of the prime numbers of the indexes of the array.
The very first step I'm just trying to do is at least to get some integer index to print out, but nothing seems to be working and I don't know what is wrong.
public class PriNum{
private boolean[] array;
public PriNum(int max){
if (max > 2){ //I don't have any problems with this if statement
throw new IllegalArgumentException();
}
else{
array = new boolean[max];
for(int i = 0; i < max; i++){
if(i == 0 || i == 1){ //Automatically makes 0 and 1 false
//because they are not prime
array[i] = false;
}
else{
array[i] = true;
}
}
toString(); //I know for sure the code gets to here
//because it prints out a string I have
// there, but not the index
}
}
public String toString(){
String s = "test"; //this only prints test so I can see if
//the code gets here, otherwise it would just be ""
for (int i = 0; i < array.length; i++){
if(array[i] == true){
s = s + i; //Initially I tried to have the indexes returned
//to be printed and separated by a comma,
//but nothing comes out at all, save for "test"
}
}
return s;
}
}
EDIT: Included is the driver class that's requesting the print of the class PriNum
class Driver{
public static void main(String [] args){
PriNum theprime = null;
try{
theprime = new PriNum(50);
}
catch (IllegalArgumentException oops){
System.out.println("Max must be at least 2.");
}
System.out.println(theprime);
}
}

I tried running this, and the first change that needs to happen is to set this argument:
if(max < 2)
Then, if I'm reading this correctly: 0 and 1 are false. Every index after that is true. The output is fine as I see it. Just all the numbers crunched as a continuous list.
To get a better output, put a space between indexes:
if(array[i] == true){
s = s + " " + i;
}
You may even just output to screen directly as
if(array[i])
System.out.print( i );

numbers is initialized without declaration, array is declared but not initialized anywhere in your code. You have also a syntax error after array[i] = true, should be curly brace...

Related

Returning different return value

When i have a problem with the code im writing, i usually handle it like a story. Each command is a sentence in a story. The sentences needs to make sense in order for the story to be complete/right.
So im learning java from scratch now with the MOOC course at Helsinki University. I got somewhat stuck at exercise 68. The program is suppose to compare integer values of a list(array) together with user input. What i programmed is a method that return true if the user input number is already on the list, and false if its not.
What I said about story at the start: The commented out code is my initial code. This did not past the last test but in my head both the commented out code and the other code say basically the same
Error message (from last test):
"Answer wrong when parameter was list [0, 7, 9, -1, 13, 8, -1] and value 8 expected: false but was: true"
public static boolean moreThanOnce(ArrayList<Integer> list, int searched)
// if (list.size()==1) {return false;}
//
// for (int i = 0; i < list.size();i++ ){
// if (list.contains(searched))
//
// {
//
// return true; }
//
// }
//return false;
//
int counter = 0;
for (int num : list) {
if (searched == num) {
counter++;
}
}
if (counter >= 2){
return true;
} else {
return false;
}
}
I understand that there is something wrong, just cant seem to figure it out. Do you see why the last code would be accepted, but not the first (commented out one) ?
If any use, the rest of the code (not my work) is this:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("Type a number: ");
int number = Integer.parseInt(reader.nextLine());
if (moreThanOnce(list, number)) {
System.out.println(number + " appears more than once.");
} else {
System.out.println(number + " does not appear more than once. ");
}
}
}
Code that is commented out guaranties only that if true there is at least one of occurance in array, maybe there are more but not guaranted. If function returns false thes may be 1 or no occurance.
Reason: If arrary os bigger than 1 it does not mean that there are 2 or more occurances of value you search for.
Posible solution: Add counter like uncommented code.
Your first algorithm has a few flaws, first you test for a length of one explicitly. Not null, and not an empty List. Second, you should prefer the List interface to the ArrayList explicit type. And finally, you need to consider the sublist offset by one of the current position when you call contains (clearly the list contains at least the current value).
I think you wanted something like
public static boolean moreThanOnce(List<Integer> list, int searched) {
if (list == null || list.size() < 2) {
return false;
}
int len = list.size();
for (int i = 0; i < len - 1; i++) {
if (list.get(i).equals(searched)
&& list.subList(i + 1, list.size()).contains(searched)) {
return true;
}
}
return false;
}
And, we can express that as generic method. Like,
public static <T> boolean moreThanOnce(List<T> list, T searched) {
if (list == null || list.size() < 2) {
return false;
}
int len = list.size();
for (int i = 0; i < len - 1; i++) {
if (list.get(i).equals(searched)
&& list.subList(i + 1, list.size()).contains(searched)) {
return true;
}
}
return false;
}
or, if you're using Java 8+, use a Stream and filter and then count like
public static <T> boolean moreThanOnce(List<T> list, T searched) {
if (list == null || list.size() < 2) {
return false;
}
return list.stream().filter(v -> v.equals(searched)).count() > 1;
}

JavaFX: Missing return statement

I have the following code that does the following:
- It takes a temperature and a channel index and searches through a list of objects (that contain temperature arrays) and returns the index of the object where the temperature is found.
I want this method to end when it finds the first one since this is the earliest time at which the temperature was reached (it's logged)
public int findRow(double targetTemperature, int ch)
{
//This method takes a double and finds it in the List, it then returns the element in which it is (the row)
//The element returned can be used with duration.between to find the response time between 2 known values
for (int i=0; i < readings.size(); i++)
{
double compareTemp = readings.get(i).getValue(ch);
if (compareTemp > targetTemperature)
{
System.out.println(readings.get(i).getTimestamp() + "is above target temp for channel " + ch);
return i;
}
else
{
System.out.println(readings.get(i).getTimestamp() + "Is not above target temp for channel " + ch);
return 0;
}
}
}
The List contains TemperatureReadings which is a class I created that has two variables:
- values array of doubles
- timestamp with currentime (when the array was created)
I'm trying to find the response time for each channel. However, when I run the above code it says that "there is no return statement" even though both options have a return statement (if/else)
Or if you can help me make a better method to find the FIRST OCCURENCE of the list where the temperature in that channel (array index) reached X degrees I would really appreciate it.
Actually I would not like it to return 0 if possible to return an error or something saying "no temperature was found" or something like that
Because your if statement is inside your loop, what happen if your loop do not run? ==> mean that you have no return statement!
Add a return statement out of your loop, although you know that it can not run this statement just because you sure the loop will run, but the compiler is not know that
Tuyen is correct. Also, you don't want the else statement. You'll return after the first item. You'll just want the first if, then outside the loop return 0;
Try:
public int findRow(double targetTemperature, int ch)
{
//This method takes a double and finds it in the List, it then returns the element in which it is (the row)
//The element returned can be used with duration.between to find the response time between 2 known values
for (int i=0; i < readings.size(); i++)
{
double compareTemp = readings.get(i).getValue(ch);
if (compareTemp > targetTemperature)
{
System.out.println(readings.get(i).getTimestamp() + "is above target temp for channel " + ch);
return i;
}
}
System.out.println(readings.get(i).getTimestamp() + "Is not
above target temp for channel " + ch);
return -1;
}
Your loop is incorrect: If the first element does not fit the condition, the method will return in the else branch without even checking the other elements of the list.
You could remove the else brach, and make a convention (and javadoc comment, that -1 is returned if no item has been found with the specified criteria) ...
public int findRow(double targetTemperature, int ch) {
for (int i = 0; i < readings.size(); i++) {
if (readings.get(i).getValue(ch) > targetTemperature)
return i;
}
return -1;
}
... and you can log anything based on the return value on the caller side:
int channel = 2;
int ind = findRow(35, channel);
if (ind >= 0)
System.out.println(readings.get(ind).getTimestamp() + " is above target temp for channel " + channel);
else
System.out.println("Nothing has been found");
The same using a stream:
public int findRow(double targetTemperature, int ch) {
return IntStream.range(0, readings.size())
.filter(i -> readings.get(i).getValue(ch) > targetTemperature)
.findFirst()
.orElse(-1);
}

Looping through two separate if statements

The code below is a simplified version of a method I am working on for a java project. The method will sort through a list of items(two different categories), in this case 0,s and 1's. The code reads through an array of numbers stops at either 0 or 1 and then prints out both the 0 or one and the string of numbers following the 0 or 1. If a preceding string is a 1 or a zero then it will stop and switch to another if statement. However it only executes each statement once. However there is more in the array that it needs to read through and organize. I would like to set up some sort of loop so that it loops through the set of if statements until it has read through the entire array.
public class tester
{
public static void main(String[] args )
{
String flags[] = {"0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i,j,k,h;
int count = 0;
for (i = 0; i<flags.length; i++)
{
if (flags[i].equals("0"))
{
for (j=0; !flags[j].equals("1") ; j++)
{
count = j+1;
array[j] = flags[j];
zeros[j] = flags[j];
}
} else
if (flags[count].equals("1"))
{
j = 0;
for(k=count; !flags[k].equals("0");k++)
{
array[k] = flags[k];
j++;
ones[j-1] = flags[k];
}
}
}
for(i=0; i<zeros.length; i++)
{System.out.println(zeros[i]);}
System.out.println();
for(i=0; i<ones.length; i++)
{System.out.println(ones[i]);}
}
}
What it prints out now:
0
23
25
34
null
null
null
null
null
null
null
null
1
9
12
13
null
null
null
null
null
null
null
null
String flags[] = {"9","0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i;
boolean addingZeroes = false;
boolean addingOnes = false;
int zeroCount = 0;
int onesCount = 0;
for (i = 0; i<flags.length; i++) {
if (flags[i].equals("0")) {
zeros[zeroCount] = flags[i];
zeroCount++;
addingZeroes = true;
addingOnes = false;
} else if (flags[i].equals("1")) {
ones[onesCount] = flags[i];
onesCount++;
addingZeroes = false;
addingOnes = true;
} else if (addingZeroes) {
zeros[zeroCount] = flags[i];
zeroCount++;
} else if (addingOnes) {
ones[onesCount] = flags[i];
onesCount++;
}
}
for(i=0; i<zeroCount; i++) {
System.out.println(zeros[i]);
}
System.out.println();
for(i=0; i<onesCount; i++) {
System.out.println(ones[i]);
}
Hey, couple things were wrong. Basically, you need a little state machine where you need to know whether you are in the midst of storing the sequence after a 1 or a 0. I used the boolean values (eg addingZeroes) for that.
Then, you need to separately keep track of your element count (eg zeroCount) for each of the storage arrays. You might have 20 digits after a 0 and just 2 after a 1.
Finally, at the end, your length of your storage arrays is not what you want - you want the amount of values you ended up storing. That's why you got all those "nulls".
One other thing I noticed is that your j value is initialized always to 0 in the 0 block, so you would always be using the lowest values of the start array.

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).

Sequential search on String array in Java [duplicate]

This question already has answers here:
String Comparison in Java
(8 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am supposed to write sequential/linear search on a String array. I am very close to finishing, but part of the assignment confuses me. It says to compare the target item with successive element of the list until the target matches or target is less than the current element of the array. How can a String be more or less than another element when there is no numerical value? Maybe I'm just not thinking about it correctly. Here is my program so far:
public class SequentialSearchString {
public static boolean sequential (String[] numbers){
//Set the target item to an arbitrary String that should return true.
String T1 = "Frank";
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == T1){
return true;
}
if (numbers[i] != T1){
numbers[i] = numbers[i+1];
}
}
return false;
}
public static boolean sequential2 (String[] numbers){
//Set the target key to String that should return false.
String T2 = "Ian";
for (int i = 0; i < numbers.length; i++){
if (numbers[i] == T2){
return true;
}
if (numbers[i] != T2){
numbers[i] = numbers[i+1];
}
}
return false;
}
public static void main(String[] args) {
//Create a list of 8 Strings.
String [] numbers =
{"Ada", "Ben", "Carol", "Dave", "Ed", "Frank", "Gerri", "Helen", "Iggy", "Joan"};
//If the first target item (T1) is found, return Succuss. If not, return failure.
if (sequential(numbers) == true){
System.out.println("Success. 'T1' was found");
}
else {
System.out.println("Failure. 'T1' was not found");
}
//If the second target item (T2) is found, return Succuss. If not, return failure.
if (sequential2(numbers) == true){
System.out.println("Success. 'T2' was found");
}
else {
System.out.println("Failure. 'T2' was not found");
}
}
}
The first method works fine, but I appear to be having issues with searching for elements that are not in the list. Here is the error message I get after running the program:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at SequentialSearchString.sequential2(SequentialSearchString.java:32)
at SequentialSearchString.main(SequentialSearchString.java:50)
Success. 'T1' was found
Any help understanding the assignment and fixing the exception would be much appreciated.
numbers[i] = numbers[i+1];
Is likely to cause your ArrayIndexOutOfBoundsException.
Your clause checks i < numbers.length. So you set the bounds. However if i == numbers.length - 1 then you will try to access i+1 which is larger then your array so it is out of bounds.
For example: numbers.length is 4. So i can be
3. With i+1 you try to access numbers[4] which would be the fifth position as arrays start with 0 and numbers[3] would be the last position.
The ArrayIndexOutOfBoundsException is due to the fact you use:
for (int i = 0; i < numbers.length; i++)
and latter:
numbers[i] = numbers[i+1];
When i equals numbers.length-1 (last iteration), i+1 equals numbers.length. Then you try to read numbers[numbers.length] which is wrong (valid index is from 0 to numbers.length-1).
You've got to use :
for(int i=0;i<numbers.length-1;i++)
to prevent the exception. Now, I'm not sure it would solve your whole problem, but the Exception certainly.

Categories