What improvements can be made to this Java code for a bowling score game?

I have prepared a bowling scoring game in Java: https://github.com/chalcrow/DiusBowlingGame

I would like a critical code review to identify possible improvements. The code runs like this:

Main.java

package com.dius.bowling;

public class Main {

    private DiusBowlingGame game;

    public static void main(String() args) {
        // method to perform rolls and calculate totalscore
        DiusBowlingGame game = new DiusBowlingGame();
        // for a new game, we must advance to the 1st frame
        game.startGame();
        game.simulateGame();
    }
}

Main Interface (BowlingGame.java)

package com.dius.bowling;

/**
 * Interface for a bowling game.
 */
public interface BowlingGame {
    /**
     * roll method specifying how many pins have been knocked down
     * @param noOfPins no. of pins knocked down
     */
    void roll(int noOfPins);

    /**
     * get player's current score
     * @return player's current score
     */
    int score();
}

DiusBowlingGame.java

package com.dius.bowling;
import java.util.*;

import static com.dius.bowling.Constants.*;

/**
 * Scoring system for tenpin bowls
 */
public class DiusBowlingGame implements BowlingGame {

    ArrayList gameFrames = new ArrayList();

    public void roll (int noOfPins) {

        System.out.println("frame" + getCurrentFrameNo() + ", rolled " + noOfPins);

        doSpecialScoresForPreviousFrame(noOfPins);

        getCurrentFrame().frameScore += noOfPins;

        if (isFirstRollOfFrame()) {
            getCurrentFrame().roll1 = new Roll();
            getCurrentFrame().roll1.pinsKnockedDown = noOfPins;
            // a strike can only occur on the 1st roll - we need to check if this is a strike
            getCurrentFrame().roll1.isStrike = this.isStrike(noOfPins);
            displayScore();
            if (this.isStrike(noOfPins)) {
                advanceFrame();
            }
        }
        else {
            // this is the 2nd roll
            getCurrentFrame().roll2 = new Roll();
            getCurrentFrame().roll2.pinsKnockedDown = noOfPins;
            // a spare can only occur on the 2nd roll - we need to check if this is a spare
            getCurrentFrame().roll2.isSpare = this.isSpare(noOfPins);
            displayScore();

            advanceFrame();
        }
    }

    private void doSpecialScoresForPreviousFrame(int noOfPins) {
        if (gameFrames.size() > 1) { // there has been at least one previous frame
            // check if any additional score should be added to the previous frame
            // for a strike on the previous frame, increment that frame score by score of both rolls on the current frame
            // for a spare on the previous frame, increment that frame score by score of the 1st roll on the current frame
            if(
                    getPreviousFrame().roll1.isStrike ||
                    getPreviousFrame().roll2.isSpare && isFirstRollOfFrame()
            ) {
                getPreviousFrame().frameScore += noOfPins;
            }
        }
    }

    public BowlingFrame getCurrentFrame() {
        BowlingFrame currentFrame = gameFrames.get(gameFrames.size() - 1);
        return currentFrame;
    }

    private int getCurrentFrameNo() {
        return gameFrames.size();
    }

    public BowlingFrame getPreviousFrame() {
        return gameFrames.get(gameFrames.size() - 2);
    }

    private boolean isFirstRollOfFrame() {
        return getCurrentFrame().roll1 == null;
    }

    private boolean isSpare(int noOfPins) {
        return getCurrentFrame().roll1.pinsKnockedDown + noOfPins == pinsPerFrame;
    }

    private boolean isStrike(int noOfPins) {
        return noOfPins == pinsPerFrame;
    }

    /**
     * Activate the 1st frame of the game
     */
    public void startGame() {
        advanceFrame();
    };

    public void advanceFrame() {
        if (gameFrames.size() < framesPerGame) {
            BowlingFrame newFrame = new BowlingFrame();
            gameFrames.add(newFrame);
        }
        else completeGame();
    }

    private void completeGame() {
        // TODO: do something to render the game complete
    }

    public int score() {
        int totalGameScore = 0;

        for (int i=0; i <= gameFrames.size() - 1; i++) {
            totalGameScore += gameFrames.get(i).frameScore;
        }

        return totalGameScore;
    }

    public void simulateGame() {
        //Frame 1- strike
        roll(10);
        //Frame2
        roll(3);
        roll(0);
        //Frame3 - wipeout
        roll(0);
        roll(0);
        //Frame 4 - spare
        roll(4);
        roll(6);
        //Frame 5
        roll(2);
        roll(6);
        //Frame 6 - spare
        roll(5);
        roll(5);
        //Frame 7 - strike
        roll(10);
        //Frame 8 - strike
        roll(10);
        //Frame 9 - spare
        roll(2);
        roll(8);
        //Frame 10 -spare
        roll(0);
        roll(10);
    }

    private void displayScore() {
        System.out.println("Total score - " + score());
    }
}

BowlingFrame.java

package com.dius.bowling;

public class BowlingFrame {

    public Roll roll1 = null;
    public Roll roll2 = null;
    public int frameScore = 0;

    public BowlingFrame() {}
}

Roll.java

package com.dius.bowling;

public class Roll {

    public int pinsKnockedDown;

    public boolean isStrike;

    public boolean isSpare;

    public Roll() { }
}

java – Avoid entering invalid dates

I am developing a jsf / primefaces form to receive data from a calendar. However, in one of the tests, the user can enter an invalid date.
How can I validate this data?

onkeydown = "focusPrevOrNextByTabOrEnter (event, $ (this), & # 39 ;: input: not (: button,
: hidden) & # 39;) ">

  


Java: new in Python, the longest collatz sequence

I am new to Python and I am struggling with a task.
"Consider the following operation applied to positive integer values: if the number is even, then divide it in half, but if the number is odd, multiply it by three and add one.
Write full Python functions as described below. All functions must be named and behave exactly as specified.
syracuse fn (n) Returns the result of the operation described in the first sentence of the preceding paragraph to the integer value n.
syracuse seq (n) For the Syracuse sequence with starting point n, it returns both its length and its largest element. For example, for n = 12, the result should be the pair 10 (length) and 16 (the largest). 1 2 3
longest seq (n) For starting points up to and including n, find which gives the longest sequence. Returns both the starting point and the length of the sequence. For example, with n = 10, the longest sequence has the starting point 9 and has a length of 20 "

So far I have:

def syracuse_fn(n):
#Return  the  result  of  the  operation to the integer value n
while n > 1:
    #If n is even, divide n by 2
    if (n%2) == 0:          
        n= n//2
    #if n is odd, multiply n by 3 and add 1
    else:
        n = 3*n+1
        return n

Any idea how to solve Syracuse_seq (n) or longest_seq (n).
Any help appreciated.

java – Why is it necessary to put public static void main (String[] args)

She is the principal function of the program, that is, the principal function. It will be called every time you run your code, so the compiler will only execute the code that is within this function

If you have not had much contact with the programming and still do not know what function, do not adhere to these details, your teacher did not comment because it may not be very useful information at this time.

If you want to know the more detailed meaning For this function, see the following link:

How to insert a node between two nodes in a linked list in Java

I have a problem I do not know how to insert an element between two nodes in a linked list so far I have this code that I can do is that I must first look for the node from which it will be added I have the method is in the list that is responsible for searching the nodes but from here I don't know what else to proceed with:

public class List {

protected Nodo primero, ultimo;
T p;

public Lista() {
    primero = null;
    ultimo = null;
}

public boolean EstaVacia() {
    if (primero == null) {
        return true;
    } else {
        return false;
    }
}

public void visualizar() {
    Nodo n = primero;
    System.out.println();
    while (n != null) {
        System.out.print("(" + n.dato + ")-->");
        n = n.enlace;
    }
}

//Eliminar un nodo especifico
public void eliminar(T p) {
    if (!EstaVacia()) {
        if (primero == ultimo && p == primero.dato) {
            primero = ultimo = null;
        } else if (p == primero.dato) {
            primero = primero.enlace;
        } else {
            Nodo anterior, temporal;
            anterior = primero;
            temporal = primero.enlace;
            while (temporal != null && temporal.dato != p) {
                anterior = anterior.enlace;
                temporal = temporal.enlace;
            }
            if (temporal != null) {
                anterior.enlace = temporal.enlace;
                if (temporal == ultimo) {
                    ultimo = anterior;
                }
            }
        }
    }
}
// buscar si un elemnento se encunetra en la lista
public boolean EstaEnLaLista(T p) {
    Nodo temporal = primero;
    while (temporal != null && temporal.dato != p) {
        temporal = temporal.enlace;
    }
    return temporal != null;
}

I hope you can help me.

java – Prepare the return waiting method

Good evening, I have a jar project that is added to another java project, I initialize it and when I call the example of the read () method;
Readings readings = new readings () // calling jar;

Return string = reads.ler ();

Open a swing window for the user to enter some data and when the user finishes, returns a string.
The problem is that my class that gets readbacks .ler () always empties. I tried to use Thread to make her wait, but continue, I would like to get advice to solve this problem.

I need the method of reading inside the jar only to return when I finish everything and the application that calls the method of reading the jar to stop waiting for this to happen

java: assigning a hashmap to a model

What is the most efficient way to assign a hashmap that contains a key and a value (String) to a model of a different structure?

E.g : hashmap.put(key1,value1)
.
.
.
.hashmap.put(keyn,value);

TO

Class abc{
String STR;
Class X;
Class Y;


}

Where class X can be

Class X{
Str a;
Str b;
}

And class Y can also be considered the same.

java – Upload file to Classpath Spring

Hi I have a question what is the root path of a project "Java" with "framework Spring" to upload files from jsp, I want to upload any file from a to "Classpath" then read them on other pages, but I have no idea what codes should be used in Java Spring. Also searching online I see that they say you can upload files in many ways but I would like to know one.
If they had a example It would be helpful to understand.
"As always, any help is welcome."

java: minimum number of exchanges necessary to bring the queue to the final state that does not exceed 2 exchanges per item

Scenario or problem statement:
It's New Year's Day and everyone is in line for the Wonderland roller coaster! There are several people in the queue and each person uses a sticker that indicates their initial position in the queue. The initial positions increase by 1 from 1 in the front of the line to n in the back.

Any person in the queue can bribe the person directly in front of them to exchange positions. If two people exchange positions, they still use the same label that denotes their original places online. One person can bribe a maximum of two others. For example, if n = 8 and Person 5 bribes Person 4, the queue will look like this: 1,2,3,5,4,6,7,8.

Fascinated by this chaotic tail, you decide that you should know the minimum number of bribes that were carried out so that the tail reaches its current state!

Descriptive function
Complete the minimalBribes function in the editor below. You must print an integer that represents the minimum number of bribes needed, or Too chaotic if line configuration is not possible.

minimumBribes has the following parameters:

q: an array of integers

Input format
The first line contains an integer, the number of test cases.

Each of the following pairs of lines is as follows: – The first line contains an integer, the number of people in the queue – The second line has whole numbers separated by spaces that describe the final state of the queue.

Output format
Print an integer that indicates the minimum number of bribes needed for the queue to reach its final state. Print Too chaotic if the state is invalid, that is, it requires one person to bribe more people.

Sample Entry

2
8
5 1 2 3 7 8 6 4
8
1 2 5 3 7 8 6 4

Sample output

Too chaotic
7

Basically, I am trying to create a method that accepts the queue values ​​in this (final) state and returns the number of bribes needed to reach the final state from 1,2,3,4,5, … Indicate , in case the number of bribes per person in the queue is not more than 2 "Too chaotic".

The code that fails in some cases when using Java Streams is the following, I want to know why I cannot achieve the output with Java Streams.

static void minimumBribes(int() q) {

        AtomicInteger bribeCount = new AtomicInteger(0);
        AtomicReference chaoticString = new AtomicReference();

        IntStream.rangeClosed(1, q.length).forEach(i -> {
            if (q(i - 1) > i) {
                if (q(i - 1) - i > 2) {
                    chaoticString.set("Too chaotic");
                } else {
                    bribeCount.addAndGet(q(i - 1) - i);
                }
            }
        });

        if (chaoticString.get() == "Too chaotic")
            System.out.print(chaoticString.get());
        else
            System.out.print(bribeCount.get());

    }

The code that passes without using Java sequences is given below:

static void minimumBribes(int() q) {

        for (int i = 0; i < q.length; i++) {
            if (q(i) - (i + 1) > 2) {
                System.out.println("Too chaotic");
                return;
            }
        }

        int bribe = 0;
        for (int i = 0; i < q.length; i++) {
            for (int j = i + 1; j < q.length; j++) {
                if(q(i) > q(j)) {
                    q(j) = q(i) + q(j);
                    q(i) = q(j) - q(i);
                    q(j) = q(j) - q(i);
                    bribe++;
                }
            }
        }
        System.out.println(bribe);
    }

**Below is the complete code except for the method:**
public class MaximumTwoBribesAllowedForMovingForwardInQueue {

//Method that needs to be filled in
    static void minimumBribes(int() q) {

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String() args) {
        int t = scanner.nextInt();
        scanner.skip("(rn|(nru2028u2029u0085))?");

        for (int tItr = 0; tItr < t; tItr++) {
            int n = scanner.nextInt();
            scanner.skip("(rn|(nru2028u2029u0085))?");

            int() q = new int(n);

            String() qItems = scanner.nextLine().split(" ");
            scanner.skip("(rn|(nru2028u2029u0085))?");

            for (int i = 0; i < n; i++) {
                int qItem = Integer.parseInt(qItems(i));
                q(i) = qItem;
            }
            minimumBribes(q);
        }
        scanner.close();
    }
}

Can you help me recommend changes if there are any to achieve this with Java transmissions?

Sample input:

2
8
5 1 2 3 7 8 6 4
8
1 2 5 3 7 8 6 4

Expected correct output:
Too chaotic
7 7

Actual incorrect output:
Too chaotic
6 6

java – Why don't you execute what is inside my onResponse

I try to send data through valley, watching a tutorial and some documentation try to make a record, what I did was put the record into a method, but nothing that is inside my onResponse is executed, I made impressions on the console (logcat) and nothing, I have days trying to make it work but nothing, if someone can help me thanks.

package com.monicar;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import fr.ganfra.materialspinner.MaterialSpinner;

public class Registro_Usuario extends AppCompatActivity implements View.OnClickListener {

EditText txtNombre, txtFecha, txtApellido, txtCorreo, txtContracena, txtCcontracena;
RadioButton rbtnhombre, rbtnmujer;
RadioGroup bxsexo;
Button Registrar;
String Sexo;
TextInputLayout impnombre, impapellido, impcontracena, impccontracena, impfecha, impcorreo;
boolean nom, ap, corr, con, fech, ccon, ccon1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registro__usuario);
    getSupportActionBar().hide();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


    txtNombre = (EditText) findViewById(R.id.edtNombre);
    txtApellido = (EditText) findViewById(R.id.edtApellido);
    txtCorreo = (EditText) findViewById(R.id.edtCorreoRe);
    txtContracena = (EditText) findViewById(R.id.edtContrasenaRe);
    txtCcontracena = (EditText) findViewById(R.id.edtCcontrasenaRe);
    txtFecha = (EditText) findViewById(R.id.edtFnacimientoRe);

    impnombre = (TextInputLayout) findViewById(R.id.impNombre);
    impapellido = (TextInputLayout) findViewById(R.id.impApellidos);
    impcorreo = (TextInputLayout) findViewById(R.id.impCorreoRe);
    impcontracena = (TextInputLayout) findViewById(R.id.impContrasenaRe);
    impccontracena = (TextInputLayout) findViewById(R.id.impCcontrasenaRe);
    impfecha = (TextInputLayout) findViewById(R.id.impFnacimientoRe);
    bxsexo = (RadioGroup) findViewById(R.id.boxSexo);


    txtFecha.setOnClickListener(this);
    rbtnhombre = (RadioButton) findViewById(R.id.rBtnHombre);
    rbtnmujer = (RadioButton) findViewById(R.id.rBtnMujer);
    Registrar = (Button) findViewById(R.id.btnRegistrar);


    Registrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            comprobarCampos();
            imprimir_RadioButton();
            Snackbar.make(view, "El Sexo elegido es: " + Sexo, Snackbar.LENGTH_SHORT).show();
        }
    });


}

//nom, ap, corr,con,fech,ccon,conn1
private void comprobarCampos() {

    if (txtNombre.getText().toString().isEmpty()) {
        impnombre.setError("Este campo es requerido");
        nom = false;
    } else {
        nom = true;
        impnombre.setError(null);
    }

    if (txtApellido.getText().toString().isEmpty()) {
        impapellido.setError("Este campo es requerido");
        ap = false;
    } else {
        impapellido.setError(null);
        ap = true;
    }

    if (Patterns.EMAIL_ADDRESS.matcher(txtCorreo.getText().toString()).matches() == false) {
        impcorreo.setError("Correo invalido");
        corr = false;
    } else {
        impcorreo.setError(null);
        corr = true;
    }

    if (txtContracena.getText().toString().isEmpty()) {
        impcontracena.setError("Este campo es requerido");
        con = false;
    } else {
        impcontracena.setError(null);
        con = true;
    }

    if (txtCcontracena.getText().toString().isEmpty()) {
        impccontracena.setError("Este campo es requerido");
        ccon = false;
    } else {
        impccontracena.setError(null);
        ccon = true;
    }



if(!txtCcontracena.getText().toString().equals(txtContracena.getText().toString())) {

    impccontracena.setError("Las contraceñas no coinciden");
    ccon1 = false;
} else {
    impccontracena.setError(null);
    ccon1 = true;
}

    if (txtFecha.getText().toString().isEmpty()) {
        impfecha.setError("Este campo es requerido");
        fech = false;
    } else {
        impfecha.setError(null);
        fech = true;
    }


    if (rbtnhombre.isChecked() == true) {
        Sexo = "Hombre";
    } else if (rbtnmujer.isChecked() == true) {
        Sexo = "Mujer";
    } else {
        Toast.makeText(this, "Seleccione un Sexo", Toast.LENGTH_LONG).show();
    }

In the condition that follows we move to the method in case all the following conditions are met.

    if (nom == true && ap == true && corr == true && con == true && fech == true && ccon == true && ccon1 == true) {
        registroBd();
    } else
        Toast.makeText(this, "Faltan Datos", Toast.LENGTH_LONG).show();


//nom, ap, corr,con,fech,ccon,conn1


}

In this part is the onResponse method
As you can see there are the impressions in the logcat but they do not appear at the time of making a record, and it does not send any errors.

private void registroBd() {
    String nombre, apellido, correo, contrasena, fecha, sexo;
    nombre = txtNombre.getText().toString();
    apellido = txtApellido.getText().toString();
    correo = txtCorreo.getText().toString();
    contrasena = txtContracena.getText().toString();
    fecha = txtFecha.getText().toString();
    sexo = Sexo;

    Log.d("registroBd", "Datos Obtenidos nombre:" + nombre + "apellido:" + apellido + "correo:" + correo + "contra:" + contrasena + "fecha:" + fecha + "sexo:" + sexo);

    Response.Listener respuesta = new Response.Listener() {
        @Override
        public void onResponse(String response) {
            Log.d("onresponse", "Inicio");
            try {
                JSONObject json_respuesta = new JSONObject(response);
                boolean ok = json_respuesta.getBoolean("success");
                if (ok == true) {
                    Log.d("Entrotry", "Inicio");
                    Intent i = new Intent(Registro_Usuario.this, Login.class);
                    Registro_Usuario.this.startActivity(i);
                    //Registro_Usuario.this.finish();
                    Log.d("Entrotry", "Salio");
                } else {
                    Log.d("Fallo", "no jalo");
                    AlertDialog.Builder alerta = new AlertDialog.Builder(Registro_Usuario.this);
                    alerta.setMessage("Fallo en el Registro")
                            .setNegativeButton("Reintentar", null)
                            .create()
                            .show();

                }
            } catch (JSONException e) {
                e.getMessage();
            }
        }
    };
    Log.d("RegistroRequest", "Inicio");
    RegistroRequest r = new RegistroRequest(nombre, apellido, correo, contrasena, fecha, sexo, respuesta);
    RequestQueue cola = Volley.newRequestQueue(Registro_Usuario.this);
    cola.add(r);
    Log.d("Request", "Fin");

}

private void imprimir_RadioButton() {
    if (rbtnhombre.isChecked() == true) {
        Sexo = "Hombre";
    } else if (rbtnmujer.isChecked() == true) {
        Sexo = "Mujer";
    } else {
        Toast.makeText(this, "Seleccione un Sexo", Toast.LENGTH_LONG).show();
    }


    //Toast.makeText(this, "El Sexo Seleccionado es :"+Sexo, Toast.LENGTH_LONG).show();
}


@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.edtFnacimientoRe:
            showDatePickerDialog();
            break;
    }
}

private void showDatePickerDialog() {
    DatePickerFragment newFragment = DatePickerFragment.newInstance(new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            // +1 because January is zero
            final String selectedDate = day + " / " + (month + 1) + " / " + year;
            txtFecha.setText(selectedDate);
        }
    });

    newFragment.show(getSupportFragmentManager(), "datePicker");
}

}