Math.round not working?

Hey everyone!
I’m doing this optional project for Computer Science class in School, this semester we’re studying Java.

I’m having trouble getting this GUI code to work.

The error Message says: incompatible types; possible lossy conversion from double to int.

Here’s a screenshot of my code:

also, ignore the fact that the Decimal Format code, I hoped that would work to fix it, but it didn’t. (Problem still exsists)

P.S. I am aware I don’t have the code to set the text in the output

Here’s the code
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

/**
*

  • @author User
    /
    import java.util.
    ;
    public class U2A3_RandomNumberGenerator_JosiahArmstrong_GUI extends javax.swing.JFrame {

    /**

    • Creates new form U2A3_RandomNumberGenerator_JosiahArmstrong_GUI
      */
      public U2A3_RandomNumberGenerator_JosiahArmstrong_GUI() {
      initComponents();
      }

    /**

    • This method is called from within the constructor to initialize the form.

    • WARNING: Do NOT modify this code. The content of this method is always

    • regenerated by the Form Editor.
      */
      @SuppressWarnings(“unchecked”)
      //
      private void initComponents() {

      jLabel1 = new javax.swing.JLabel();
      jLabel2 = new javax.swing.JLabel();
      minNumber = new javax.swing.JTextField();
      jLabel3 = new javax.swing.JLabel();
      maxNumber = new javax.swing.JTextField();
      randomButton = new javax.swing.JButton();
      randomOutput = new javax.swing.JLabel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      jLabel1.setText(“Number Generator 9000”);

      jLabel2.setText(“Minimum Number”);

      jLabel3.setText(“Maximum Number”);

      randomButton.setText(“Generate”);
      randomButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      randomButtonActionPerformed(evt);
      }
      });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addContainerGap()
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addComponent(jLabel1)
      .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      .addGroup(layout.createSequentialGroup()
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
      .addComponent(minNumber, javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
      .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(maxNumber))
      .addGap(34, 34, 34))))
      .addGroup(layout.createSequentialGroup()
      .addGap(149, 149, 149)
      .addComponent(randomButton)
      .addGap(0, 174, Short.MAX_VALUE))
      .addGroup(layout.createSequentialGroup()
      .addContainerGap()
      .addComponent(randomOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGap(34, 34, 34))
      );
      layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addContainerGap()
      .addComponent(jLabel1)
      .addGap(27, 27, 27)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(jLabel2)
      .addComponent(jLabel3))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(minNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      .addComponent(maxNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
      .addComponent(randomButton)
      .addGap(18, 18, 18)
      .addComponent(randomOutput, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
      .addContainerGap())
      );

      pack();
      }//

    private void randomButtonActionPerformed(java.awt.event.ActionEvent evt) {
    double min = Double.parseDouble(minNumber.getText());
    double max = Double.parseDouble(maxNumber.getText());

     Math.round(min);
     Math.round(max);
     
     Random rand = new Random();
     int randomNumber = rand.nextInt(max - min + 1) - min;
     randomOutput.setText("Your Random numbers are: " + randomNumber);
    

    }

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /
      Set the Nimbus look and feel /
      //
      /
      If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if (“Nimbus”.equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
        }
        }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(U2A3_RandomNumberGenerator_JosiahArmstrong_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(U2A3_RandomNumberGenerator_JosiahArmstrong_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(U2A3_RandomNumberGenerator_JosiahArmstrong_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(U2A3_RandomNumberGenerator_JosiahArmstrong_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new U2A3_RandomNumberGenerator_JosiahArmstrong_GUI().setVisible(true);
      }
      });
      }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField maxNumber;
    private javax.swing.JTextField minNumber;
    private javax.swing.JButton randomButton;
    private javax.swing.JLabel randomOutput;
    // End of variables declaration
    }

Sorry if its alot, this is for a GUI

Please ignore the link within the code, that is just default in the program I use

Hands up, I don’t know java. But I think - min below might be your problem?

You’ve called Math.round() on it just above this, but not assigned the result to a variable. So perhaps min here is not an integer/long.

In which case you can’t assign the result of this formula to an int; you’ve generated an int with the first part of the expression, but then subtracted min (I think a non-int) from it, thus creating a non-integer.

In any case, Math.round() returns a long, so I’d be tempted to define randomNumber as a long, too.

int randomNumber = rand.nextInt(max - min + 1) - min;

@antonjw these lines of code take what I put in the text fields I created, and turn them into decimal numbers.

Understood.

But I still think the problem is

int randomNumber = rand.nextInt(max - min + 1) - min;

Because a double is a floating point number. So in the above statement, you’re creating a random integer, then subtracting a double (min) from it, which is going to evaluate to a double (i.e. a number with decimal places); and then you’re attempting to assign that to an int.

I think you’ll need to round min before (so creating or in the above line of code.

I have 2 different rounding lines of code (Math.round(min) and Math.round(max)) these lines round the decimals to the nearest integer

The Math.round() function is returning the result but you’re not storing it - you’re not assigning the result to a variable, so you’ve discarded the rounded result.

Should be something like

minInt = Math.round(min);
maxInt = Math.round(max);

And then use those in your randomNumber expression.

I can’t give you exact syntax though because I don’t know java. But I’m certain you’re passing min & max into your randomNumber assignment as doubles.

See here for correct syntax(es): https://alvinalexander.com/java/how-to-round-float-double-to-int-integer-in-java

    private void randomButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        double min = Double.parseDouble(minNumber.getText());
        double max = Double.parseDouble(maxNumber.getText());
        
        int minInt = Math.round(min);
        int maxInt = Math.round(max);
        
        Random rand = new Random();
        int randomNumber = rand.nextInt(maxInt - minInt + 1) - minInt;
        randomOutput.setText("Your Random numbers are: " + randomNumber);
    }                                            

ok, now the lines int minInt = Math.round(min); and int maxInt = Math.round(max); are coimg up errors.

I know you said to do minInt and maxInt without the int, but otherwise it isn’t a variable.
The error message is still the same

ok, looks like you may need to cast the result of Math.round to an int before assigning it to your new int…

try this syntax. any better?

int minInt = (int) Math.round(min);
int maxInt = (int) Math.round(max);

refs:
2nd answer here: https://stackoverflow.com/questions/2143476/how-to-cast-a-double-to-an-int-in-java-by-rounding-it-down
and last suggestion here: https://alvinalexander.com/java/how-to-round-float-double-to-int-integer-in-java

In class, we aren’t using typecasting (which is the (int))

gotta google things then!
there’s a built-in function on the double that gives you the int value.

Double myDouble = new Double("32.90");
int i = myDouble.intValue();

yeah, we’re supposed to use the Math.round(); function though

I hope I don’t get low marks for using that code xD

instead then, switch the ints involved in this to longs.

long minLong = Math.round(min);
long maxLong = Math.round(max);

and

long randomNumber = rand.nextLong(maxLong - minLong + 1) - minLong;

does this work?

This topic is solved.