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;

}

}

Polyline between to locations not snapped to road

I’m trying to draw a smooth polyline between two locations that are some distance apart (say over 100 miles) on a Google Map in Android. I’ve been following this guide and also this guide in terms of utilising the Directions and Snap to Roads API, yet due to the limit of 100 coordinates from the Snap to Roads API, it appears it is virtually impossible to draw a smooth polyline from one location to another that follows the smooth contours of the road.

I’ve managed to extract all coordinates of the directions to plot a polyline using the returned overview_points and have decoded this using the decode method from the PolyUtil API, yet the polyline drawn on the map is not snapped to the road for the vast majority of the time. Instead, I’ve tried using the Snap to Roads API and set a limit of 100 coordinates (maximum GPS points allowed) that all seem to be very accurately snapped to the road from destination A to B (only covering some distance between the two locations if far apart).

Basically, is there something I am missing entirely, or is it a case of coming up with some resolution to spread the 100 coordinates allocation of the Snap to Roads API using the GPS points retrieved from the overview_points from the Directions API, i.e. plot a coordinate every XXX meters.

Here is the bulk of the code I’ve implemented through a Volley request minus the Snap to Roads request, which the later is fairly straightforward to implement:

StringRequest stringRequest = new StringRequest(Request.Method.GET, 
"https://maps.googleapis.com/maps/api/directions/json?
origin=START_LOCATION_HERE&destination=END_LOCATION_HERE&key=API_KEY_HERE",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    JSONObject directions;
                    try {
                        directions = new JSONObject(response);

                        JSONArray routes = directions.getJSONArray("routes");

                        mCoordinates = new ArrayList<>();
                        for (int i = 0; i < routes.length(); i++) {
                            JSONObject routesObject = routes.getJSONObject(i);

                            JSONObject overviewPolyline = routesObject.getJSONObject("overview_polyline");
                            String points = overviewPolyline.getString("points");
                            String formattedResponse = points.replaceAll("'\'", "''");

                            List<LatLng> coordinates = new ArrayList<>();
                            coordinates.addAll(PolyUtil.decode(formattedResponse));

                            PolylineOptions routeCoordinates = new PolylineOptions();
                            for (LatLng latLng : coordinates) {
                                routeCoordinates.add(new LatLng(latLng.latitude, latLng.longitude));
                            }
                            routeCoordinates.width(5);
                            routeCoordinates.color(Color.BLUE);

                            Polyline route = mGoogleMap.addPolyline(routeCoordinates);
                            for (LatLng latLng : coordinates) {
                                mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)));
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO handle error
        }

    });