Handling data return types with Mybatis SQL Builder

I am relatively new to Java MyBatis. I came across SQL Builder class in MyBatis. However, I don’t understand how to handle the result of the SQL call, especially if the columns are going to be different in each case. Is there an example which can help me understand how to write this?

Usually, I use Mapper XML files with ResultMap to retrieve the output of an SQL statement.

Beginner Java Loop Q

I am having a hard time understanding java loops when not using an asterisk to loop. How would one write the solution for this:

Write a for loop that prints the integers 0 through 9, separated by spaces.

Thank you for the help. I and trying to understand how the <= x; x++ would work? Would the x just be 22 for the number of instances?

Status Not Sending to All Clients

Hi I am making a Hangman came in Java, if the client guesses the correct word I make them wait until all clients have finished by locking the lock. When the lock is finished waiting I send back to each client everyones score.

Inside my run method I have this code:

try {

                    System.out.println("Just connected to " + server.getRemoteSocketAddress() + " PlayerId = " + id);
                    in = new DataInputStream(server.getInputStream());
                    out = new DataOutputStream(server.getOutputStream());

                    out.writeUTF(myMap.get(id).toString());
                    /* Echo back whatever the client writes until the client exits. */
                    while (!line.equals("exit")) {
                        if (in.available() > 0) {

                            line = in.readUTF();
                            String usedList = myMap.get(id).get(0);

                            if (!hasBeenUsed(line, usedList)) {
                                int counter = Integer.parseInt(myMap.get(id).get(2)) + 1;

                                String newUsedList = UsedLetters(line, usedList);
                                char[] myEncryptedMovie = null;
                                myEncryptedMovie = myMap.get(id).get(1).toCharArray();

                                ArrayList<String> tempList = new ArrayList<String>();

                                tempList.add(newUsedList);
                                tempList.add(decryptedMovie(line, myEncryptedMovie));
                                tempList.add("" + counter);
                                tempList.add("false");

                                myMap.put(id, tempList);

                            }

                            if (myMap.get(id).get(1).equals(selectedMovie) || line.equals(selectedMovie)) {
                                String complete = myMap.get(id).get(3);
                                complete = "true";
                                myMap.get(id).set(3, complete);

                                if (!IsComplete(myMap))           
                                {               

                                    waiter();
                                    out.writeUTF("ALL COMPLETE!");

                                }
                                else{
                                    AllComplete();
                                    System.out.println("AFTER COMPLETE: " + line);
                                    out.writeUTF("ALL COMPLETE!");
                                }



                            } else {

                                    System.out.println("REGULAR CHECK: " + line);
                                out.writeUTF(myMap.get(id).toString());
                            }
                        }
                    }


                } catch (SocketTimeoutException s) {
                    System.out.println("Socket timed out!");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException ex) {
                    Logger.getLogger(HangmanControl.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "nGoodbye!");
                    } catch (IOException ex) {
                        Logger.getLogger(HangmanControl.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    // }
                }

If you look near the bottom of my try catch I have this block:

if (myMap.get(id).get(1).equals(selectedMovie) || line.equals(selectedMovie))

I check to see if the stored decryptedMovie is the same as the selectedMovie (which is our word to be guessed) or if the current word they have typed in is the selectedMovie.

I call isComplete:

public boolean IsComplete(ConcurrentHashMap<Integer, ArrayList<String>> map)
    {
         int counter = 0;

         for (int i = 101; i <= map.size() + 100; i++) {
                //System.out.println((myMap.get(i).get(3)));
                if ((map.get(i).get(3)).equals("true")) {
                    counter++;
                }
            }

            if (map.size() == counter) {
                return true;
            } else {
                return false;
            }
    }

Which will check if position 3 in my arraylist is “true” if so count them all and if it is the same size as the map then we know all users are complete and call AllComplete. If not we send false which will call waiter().

AllComplete:

public void AllComplete() throws InterruptedException {
    synchronized (lock) {
       allDone = true;
       lock.notifyAll();
    }

}

waiter:

public void waiter() throws InterruptedException, IOException {
        synchronized (lock) {
        while (!allDone) {           
           lock.wait();                       
           System.out.println("after waiting....");           
        }
           System.out.println("after allDone");      
        }
    }

My issues comes after waiter is called when I know allDone is true it finishes the loop and goes back and should print out.writeUTF("ALL COMPLETE!"); back to the client. But it doesn’t, I’m not sure why it doesn’t send it back. I know my lock.wait has finished because it will successfully print “after waiting….” and “after allDone”. However, if I had a 2nd client who also completed it. They will see “ALL COMPLETE” because they won’t hit the waiter() if statement. My first client sees nothing but is allowed to type again and because their data was already saved in the hashmap it doesn’t go into the waiter() if statement and just hits the “ALL COMPLETE”. How can I get the out.writeUTF to display the first time and not after the first client types again?

Expand and collapse Relativelayout by button click

I have this RelativeLayout which expand and collapse on button click
it works fine on one button.
I want to reuse same method on more two RelativeLayout
in same layout
and expand using other two buttons.

This code is running fine. just want more layout to do same action.

Layout:
enter image description here

This is my code:

    <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout

            android:layout_width="fill_parent"
            android:layout_height="64dp"
            android:background="#FFF"
            android:orientation="vertical">

            <TextView

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Title"
                android:textSize="20sp" />

            <Button
                android:id="@+id/viewmore"
                android:layout_width="80dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="280dp"
                android:background="@null"
                android:text="viewmore" />


        </RelativeLayout>


        <RelativeLayout

            android:id="@+id/expandable"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true"
            android:background="@color/colorAccent"
            android:orientation="vertical">


            <TextView

                android:layout_width="match_parent"
                android:layout_height="133dp"
                android:text="Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters"
                android:textSize="20sp" />


        </RelativeLayout>


        <RelativeLayout


            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Title 2"
                android:textSize="20sp" />

            <Button
                android:id="@+id/viewmore1"
                android:layout_width="80dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="280dp"
                android:background="@null"
                android:text="viewmore" />


        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/expandable1"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginTop="30dp"
            android:background="@color/colorPrimary">

            <TextView

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters"
                android:textSize="20sp" />


        </RelativeLayout>

        <RelativeLayout

            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Title 3"
                android:textSize="20sp" />

            <Button
                android:id="@+id/viewmore2"
                android:layout_width="80dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="280dp"
                android:background="@null"
                android:text="viewmore" />


        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/expandable2"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginTop="30dp"
            android:background="@color/colorPrimary">

            <TextView

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting of alphabetic and numeric characters"
                android:textSize="20sp" />


        </RelativeLayout>


    </LinearLayout>
</ScrollView>

Source Code:

RelativeLayout relativeLayout, relativeLayout1, relativeLayout2;
    Button viewmore, viewmore1, viewmore2;
    ValueAnimator mAnimator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewmore);


        relativeLayout = (RelativeLayout) findViewById(R.id.expandable);
        relativeLayout1 = (RelativeLayout) findViewById(R.id.expandable1);
        relativeLayout2 = (RelativeLayout) findViewById(R.id.expandable2);


        viewmore = (Button) findViewById(R.id.viewmore);
        viewmore1 = (Button) findViewById(R.id.viewmore1);
        viewmore2 = (Button) findViewById(R.id.viewmore2);

        viewmore.setOnClickListener(this);
        viewmore1.setOnClickListener(this);
        viewmore2.setOnClickListener(this);


        relativeLayout.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {

                    @Override
                    public boolean onPreDraw() {
                        relativeLayout.getViewTreeObserver().removeOnPreDrawListener(this);
                        relativeLayout.setVisibility(View.GONE);

                        final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                        final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                        relativeLayout.measure(widthSpec, heightSpec);

                        mAnimator = slideAnimator(0, relativeLayout.getMeasuredHeight());
                        return true;
                    }
                });


    }


    private void expand() {

        relativeLayout.setVisibility(View.VISIBLE);
        mAnimator.start();
    }

    private void collapse() {
        int finalHeight = relativeLayout.getHeight();

        ValueAnimator mAnimator = slideAnimator(finalHeight, 0);

        mAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animator) {
                //Height=0, but it set visibility to GONE
                relativeLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationStart(Animator animator) {
            }

            @Override
            public void onAnimationCancel(Animator animator) {
            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
        mAnimator.start();
    }


    private ValueAnimator slideAnimator(int start, int end) {

        ValueAnimator animator = ValueAnimator.ofInt(start, end);


        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                //Update Height
                int value = (Integer) valueAnimator.getAnimatedValue();

                ViewGroup.LayoutParams layoutParams = relativeLayout.getLayoutParams();
                layoutParams.height = value;
                relativeLayout.setLayoutParams(layoutParams);
            }
        });
        return animator;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.viewmore:

                if (relativeLayout.getVisibility() == View.GONE) {
                    expand();
                } else {
                    collapse();
                }

                break;


            case R.id.viewmore1:


                break;

            case R.id.viewmore2:


                break;


        }
    }

Overlaying slider element on top of CardView

I am trying to build a slider that slides on top of my current view in Android. I built the slider using the SlideUp library found here https://github.com/mancj/SlideUp-Android. The slider is taking the inner RelativeLayout as a view source. When I pull up the slider it ends up behind the CardView. I’ve looked through all the methods in the library and there isn’t one that allows you to move the slider to the foreground. I’ve also tried to bring the slider view to foreground with .bringToFront() method. Moving the slider view before the CardView in the .xml file does nothing either. Is there a good way to bring the slider to foreground… or the CardView in the background? (without hiding the CardView)

JAVA

//code to build slider
View slideView = findViewById(R.id.slider);
//tried putting slideView.bringToFront() here before passing it to the object but that did nothing

SlideUp slideUp = new SlideUpBuilder(slideView)
        .withStartState(SlideUp.State.HIDDEN)
        .withStartGravity(Gravity.BOTTOM)
        .build();

//code to bring up slider. View "share" exists, it's just irrelevant so I didn't include in the .xml file
buttonView.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //tried putting slideView.bringToFront() here as well
            slideUp.toggle(); //toggles slider up/down
        }
    });

XML

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:background="@color/background"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="60dp">
    </android.support.v7.widget.CardView>

    <RelativeLayout
        android:orientation="vertical" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/slider"
        android:background="@color/primary">
    </RelativeLayout>

</RelativeLayout>

Java Mirror program with user input

I made a simple mirror program and now I was asked to modify it. At first I used a static value for the sizing. Now I need to use user input for the sizing. So far this is what I have but i’m not sure where to go with this. If anyone can help that would be great. The user input I get is supposed to be used for the size. Also I need to create a method named printspaces() which takes a parameter for how many spaces to print and use it to print the spaces.
create a method named printdots() which takes a parameter for how many dots to print and use it to print the dots. What code will I need to remove to add printdots and printspaces? Thanks

import java.util.Scanner;
public class Mirror_2 {
public static void main(String[] args) {
        line(0);
        top(0);
        bottom(0);
        line(0);
        int SIZE;

        Scanner Console= new Scanner (System.in);
        System.out.print("Please enter Size: ");
        int SIZE1= Console.nextInt();
        System.out.println("You entered integer " + SIZE1);

}


public static void line(int SIZE) {
    //To change the lines at the bottom and top
    System.out.print("#");
    for (int i=1; i <= SIZE * 4; i++){
    System.out.print("=");
    }
    System.out.println("#");

}

    public static void top(int SIZE) {
        //To change the top portion of the ASCII Art
        for (int line = 1; line <= SIZE; line++) {
            System.out.print("|");

            for (int space = 1; space <= (line * -2 + SIZE * 2); space++) {
                System.out.print(" ");
            }

            System.out.print("<>");

            for (int dot = 1; dot <= (line * 4 - 4); dot++) {
                System.out.print(".");
            }

            System.out.print("<>");

            for (int space = 1; space <= line * -2 +  SIZE * 2; space++) {
                System.out.print(" ");
            }

            System.out.println("|");
        }
    }
    public static void bottom(int SIZE) {
        //To change the bottom portion of the ASCII Art
        for (int line = SIZE; line >= 1; line--) {
            System.out.print("|");

            for (int space = 1; space <= line * -2 +  SIZE * 2; space++) {
                System.out.print(" ");
            }

            System.out.print("<>");

            for (int dot = 1; dot <= line * 4 - 4; dot++) {
                System.out.print(".");
            }

            System.out.print("<>");

            for (int space = 1; space <= line * -2 +  SIZE * 2; space++) {
                System.out.print(" ");
            }

            System.out.println("|");
        }
    }

    {
    }
}

How would i change this code to allow more than one user input message to be sent between the client and server

I’ve just started with both java and networking with servers and clients. Although i understand the basics of whats going on, i was struggling to put it all together and do what i wanted to do in the title.
I was able to make this to send a message to the server, however i was wondering how i’d turn the message into a input string from the user, and also how id send multiple messages between the client and server
thanks

SERVER

import java.io.;
import java.net.
;

public class Server {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    try{
        //Setup the socket for communication and accept incoming communication
        ServerSocket serverSoc = new ServerSocket(portNumber);
        Socket soc = serverSoc.accept();

        //Catch the incoming data in a data stream, read a line and output it to the console
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());
        System.out.println("--> " + dataIn.readUTF());

        //Remember to close the socket once we have finished with it.
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}   

}

CLIENT

import java.io.;
import java.net.
;

public class Client {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    //ServerIP:- IP address of the server.
    String serverIP = "localhost";

    try{
        //Create a new socket for communication
        Socket soc = new Socket(serverIP,portNumber);

        //Create the outputstream to send data through
        DataOutputStream dataOut = new DataOutputStream(soc.getOutputStream());

        //Write message to output stream and send through socket
        dataOut.writeUTF("Hello other world!");
        dataOut.flush();

        //close the data stream and socket 
        dataOut.close();
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}

}

Java map entry string casting issue

I’m making a custom irritator to use in a SortedMap with keys being strings and the values being a count of how many times that string has been read.
When I run it, I get this error:

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry
at comp2402a1.Part8$1.compare(Part8.java:21)

I can’t seem to figure out why I’m getting this casting error. Any help and insight anyone could provide would be really appreciated.

Here is my code:

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
//Custom comparator
Comparator<Map.Entry<String, Integer>> mapCompare = new Comparator<Map.Entry<String, Integer>>(){ 
  @Override
  public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
    if (o1.getValue()-o2.getValue() != 0){
      return o1.getValue()-o2.getValue(); 
    } else {
      return o1.getKey().compareTo(o2.getKey()); 
    }
  }
};

//Read lines into a HashMap & count instance #s 
HashMap<String, Integer> hMap = new HashMap(); 
for (String line = r.readLine(); line != null; line = r.readLine()) {
  if (hMap.get(line)==null) {
    hMap.put(line,1); 
    w.println("1");
  } else {
    hMap.put(line, hMap.get(line)+1);
  }
}

//Put objects into sorted map w/custom sort and output
SortedMap<String, Integer> sMap = new TreeMap(mapCompare); 
sMap.putAll(hMap);
for (Map.Entry<String, Integer> e : sMap.entrySet()){
  w.println(e.getKey()); 
}

}

Android – Firebase – Multiple Data created from Saving one Data

Aim

Users will be able to save data to Firebase Database.

Database Tree

enter image description here

Red Arrows shows the relationship between the Incident Reports and Users

Description

  1. User ID HgjqbEyrjsbbFZsMV2MycN1xQvV2 was signed into the app.

  2. The User then proceeded to save data for himself/herself

  3. Despite being the only User signed in at that moment and saving for himself ONLY, two other data was saved automatically with data retrieved from the other two users

  4. The Multiple data saved were then stored under the “Current User ID”

  5. The reason that there were TWO extra data saved, is because there are TWO other users besides the current user.

Problem

As the red arrows show, when one user saves data, extra “Data” are saved as well

Based on the Database Tree, there were THREE data saved under the on User ID. It should only be ONE data saved under that User ID.

Mathematical Formula for Problem

Number of Users (In Database) = N

Current User signed in = C

Saving Data = S

Saved Data = D

CS = DN

Mathematical Formula for Solution

CS = CD

ReportFragment Java

public class ResidentReportFragment extends Fragment {

    private String jReportDateTime;
    private EditText jReportLocationEnt;
    private EditText jReportDescriptionEnt;

    private Button jReportSendBtn;

    private FirebaseUser jReportCurrentUserID;

    private DatabaseReference jReportByUserDatabase;

    private ProgressDialog jReportLoad;

    public ResidentReportFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View viewRoot = inflater.inflate(R.layout.fragment_resident_report, container, false);

        jReportLocationEnt = viewRoot.findViewById(R.id.reportLocationEnt);
        jReportDescriptionEnt = viewRoot.findViewById(R.id.reportDescriptionEnt);

        jReportSendBtn = viewRoot.findViewById(R.id.reportSendBtn);

        jReportLoad = new ProgressDialog(getActivity());

        jReportSendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String userReportLocation = jReportLocationEnt.getText().toString();
                String userReportDescription = jReportDescriptionEnt.getText().toString();

                if(!TextUtils.isEmpty(userReportLocation)&&
                        !TextUtils.isEmpty(userReportDescription)){
                    submitReport(userReportLocation, userReportDescription);
                    jReportLoad.setTitle("Sending Report");
                    jReportLoad.setMessage("Please wait while the report is being sent");
                    jReportLoad.setCanceledOnTouchOutside(false);
                    jReportLoad.show();
                }else{
                    jReportLoad.dismiss();
                    Toast.makeText(getActivity(), "Report failed to be sent due to empty inputs", Toast.LENGTH_SHORT).show();
                }

            }
        });

        return  viewRoot;
    }

    private void submitReport(final String userReportLocation,final String userReportDescription) {

        DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
        dbRef.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    String timeStamp = new SimpleDateFormat("dd-MM-yyyy (HH:mm:ss)").format(Calendar.getInstance().getTime());
                    Users user = snapshot.getValue(Users.class);
                    HashMap<String, String> incidentReportUser = new HashMap<>();
                    incidentReportUser.put("name", user.name);
                    incidentReportUser.put("neighbourhood", user.neighbourhood);
                    incidentReportUser.put("date", timeStamp);
                    incidentReportUser.put("location", userReportLocation);
                    incidentReportUser.put("description", userReportDescription);

                    jReportCurrentUserID = FirebaseAuth.getInstance().getCurrentUser();
                    final String reportUserID = jReportCurrentUserID.getUid();
                    jReportByUserDatabase = FirebaseDatabase.getInstance().getReference().child("Incident Reports").child(reportUserID);
                    jReportByUserDatabase.push().setValue(incidentReportUser).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if(task.isSuccessful()){
                                jReportLoad.dismiss();
                                Toast.makeText(getActivity(), "Report was Sent", Toast.LENGTH_SHORT).show();
                                jReportLocationEnt.setText("");
                                jReportDescriptionEnt.setText("");
                            }else{
                                jReportLoad.dismiss();
                                Toast.makeText(getActivity(), "Report failed to be sent", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }
}

Additional Comments

  • Summary

I just want the Current User to save data for himself/herself. My current codes somehow automatically save extra data which is retrieved from the other existing “Users” (I hope my Mathematical formula helps)

  • Linked Question

Android – Firebase – Save new Data without overwriting old Data

Prevent negative numbers and return previous value in Java?

In setSpeed I am trying to have a validation check on numbers passed through. If a negative number is passed it should pass the initial value. (speed:0) but if I pass a 3 first then a negative number the value returned is 3. I for some reason can’t get 0 returned if I pass a negative number first.

{

private String type;
private double speed;


public Conveyor (String t, double s)
    {
        type = t ;
        speed = s;
        setSpeed(s);
    }

public String getType()
    {
        return type;
    }

public double getSpeed()
    {
        return speed;
    }

public void setSpeed(double s)
    {

        if (s > 0) 
        {
            speed = s;
        }
        else 
            speed = speed;


    }
public double timeToTransport (double distance)
{
    distance = distance / speed;
    return distance;

}

}