JavaFX: Missing return statement - java

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);
}

Related

How to print out the index of a boolean array?

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

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;
}

Java method that returns strings using recursion

Here is my code:
private static String recString(final int i) {
return (i>0 ? i + "." + recString(i-1) : i<0? "." + recString(i+1) : "" ) ;
}
The method should return i dots and the number of dots at begin (example recString(4) returns "4....") when i>0 and just dots when i<=0 (example recString(-4) returns "...."). The condition is that I use just one return line any other modification is not allowed. All I get "4.3.2.1." when I call recString(4). I see where is the problem but cant figure out how to take variable just at the beginning and not change it ? Thanks in advance
As for a positive number you have to output the initial number only once, and you can only output that number in the 'positive' branch, you have to leave that 'positive' branch after one iteration.
A possible solution is to negate your number after you output it in your 'positive' branch and then allow the 'negative' branch to finish the job (output all the dots):
return (i > 0 ? i + recString(-i) : i < 0 ? "." + recString(i + 1) : "");
The initial code of the question author worked for non-negative numbers. The suggested sulution makes it work for positive ones too.
If non-recursive solutions are allowed, you can use
public static String recString(final int length) {
return String.format("%d%" + length + "s", length, "").replace(' ', '.');
}
Which returns "1." for length = 1, "2.." for length = 2, and so on, but fails for length < 1. If you also need the non-positive numbers, you can use:
public static String recString(final int length) {
return length < 1
? length + ""
: String.format("%d%" + length + "s", length, "").replace(' ', '.');
}
By the way: »Only one return line« could also mean that your you are allowed to write functions like the following.
public static String recString(final int length) {
String result;
// do something
return result;
}
if i value is >0 i is appended to a StringBuilder and then i dots follow otherwise i dots are appended to this StringBuilder, finally a String is returned from the our StringBuilder using toString method.
private static String recString(final int i) {
StringBuilder recString= new StringBuilder();
if (i > 0) {
recString.append(i);
for (int x = 0; x < i; x++) {
recString.append(".");
}
} else {
for (int x = 0; x > i; x--)
recString.append(".");
}
return recString.toString();
}

Why does my function only return 0 when searching through strings to find certain sub strings?

The point of this function is to search through the string to find substrings such that it starts with "foo" and ends in "bar".
E.g. foobar should return 1. foobarafoobbbarabar should return 5 because the first foo and the bar right after it count as 1, the first foo and the last bar count as another 1, the second foo and the bar that starts 3 chars after count as another 1 and finally the second foo and the last bar also count as 1, totalling 5.
Currently, i've set my function up to work like this:
public static int foobarCounter(String s)
{
int count = 0;
while(s.length() >0)
{
int startCharacter = 4; //Start character to check for bar start right after the last character of foo
while(startCharacter + 2 < s.length()) //Prevent a string out of bounds exception
{
if(s.startsWith("foo"))
{
if(s.substring(startCharacter, startCharacter + 2) == "bar")
{
++count; //add one to the count of foobars
}
else
{
++startCharacter; //else check from the start one more character along
}
}
else
{
s.replace(s.substring(0,1), ""); //Doesn't start with foo, remove the first character and try again
}
} //End of inner while loop
} //End of while loop
return count;
} //End of method
I hope this makes sense. Thankyou
Because this:
s.substring(startCharacter, startCharacter + 2)
Only returns 2 characters, not 3. So your if-statement will never be true. Make it +3
if (s.substring(startCharacter, startCharacter + 3).equals("bar"))
You should be using equals (or equalsIgnoreCase if there is a chance the value can have capitals) instead of ==
With this, you should also change the conditions of your while-loop
If it is an option for you to rewrite the function I would use something like the following. It's not a perfect solution but suitable if the data isn't too large.
public static int foobarCounter(String s) {
int count = 0;
String p1 = "foo";
String p2 = "bar";
int i = 0;
int j = 0;
while ((j = i = s.indexOf(p1, i)) != -1) {
while ((j = s.indexOf(p2, j + p1.length())) != -1) {
//the extended stepwidth of the previous line depends on p1, p2 and is not always possible like this
++count;
}
i = i + 1;
}
return count;
}

List collections interface in java

Please find below a function in my code:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id,
List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
int yes = 0;
mListPosChanged = mListPos;
//--------------------------------------------------------------------------
for (int crfLinesMainIter = begin; crfLinesMainIter < end; ) {
System.out.println(crfLines.get(crfLinesMainIter));
//---------------------------------------------------------------------------
//the total number of attributes without orthographic features
//in a crfLine excluding the class attribute is 98
if (!crfLines.get(crfLinesMainIter).equals("") && crfLines.get(crfLinesMainIter).split("\\s").length == 98) {
//in mList parenthesis are represented by the symbol
//in crfLines parenthesis are represented by -LRB- or -RRB-
//we make a check to ensure the equality is preserved
if(val.equals(crfLines.get(crfLinesMainIter).split("\\s")[0])) {
yes = checkForConsecutivePresence(crfLinesMainIter, mList, mListPos, id, crfLines);
if (yes > 0) {
mListPosChanged += yes;
System.out.println("formCrfLinesWithMentionClass: "+mListPosChanged);
for (int crfLinesMentionIter = crfLinesMainIter;
crfLinesMentionIter < crfLinesMainIter + yes;
crfLinesMentionIter++) {
String valString = "";
if (crfLinesMentionIter == crfLinesMainIter) {
valString += crfLines.get(crfLinesMentionIter);
valString += " B";
crfLines.add(crfLinesMentionIter, valString);
}
else {
valString += crfLines.get(crfLinesMentionIter);
valString += " I";
crfLines.add(crfLinesMentionIter, valString);
}
}
crfLinesMainIter += yes;
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
return crfLines;
}
The problem I face is as follows:
crfLines is a List collections interface.
When the for loop (between //-----) starts out, the crfLines.get(crfLinesMainIter) works fine. But once, it enters into the if and other processing is carried out on it, even though "crfLinesMainIter" changes the crfLines.get(crfLinesMainIter) seems to get a certain previous value. It does not retrieve the actual value at the index. Has anyone faced such a scenario? Would anyone be able to tell me why this occurs?
My actual question is, when does it occur that even though the indexes might be different a list.get() function still retrieves a value from before which was at another index?
For example:
List crfLines = new LinkedList<>();
if crfLinesMainIter = 2
crfLines.get(crfLinesMainIter) brings me a value say 20 and this value 20 satisfies the if loop condition. So then further processing happens. Now when the for loop executes the values of crfLinesMainIter changes to say 5. In this case, crfLines.get(5) should actually bring me a different value, but it still brings me the previous value 20.
(Not an answer.)
Reworked (more or less) for some modicum of readability:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id, List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
mListPosChanged = mListPos;
int i = begin;
while (i < end) {
if (crfLines.get(i).equals("") || (crfLines.get(i).split("\\s").length != 98)) {
++i;
continue;
}
if (!val.equals(crfLines.get(i).split("\\s")[0])) {
++i;
continue;
}
int yes = checkForConsecutivePresence(i, mList, mListPos, id, crfLines);
if (yes <= 0) {
++i;
continue;
}
mListPosChanged += yes;
for (int j = i; j < i + yes; j++) {
String valString = crfLines.get(j);
valString += (j == i) ? " B" : " I";
crfLines.add(j, valString);
}
i += yes;
}
return crfLines;
}
What is mListPostChanged? I find it confusing that it's being set to the value of a parameter named mListPos--it makes me think the m prefix is meaningless.
What is val in the line containing the split?

Categories