当前位置: 首页 > 知识库问答 >
问题:

long到int可能有损转换?[重复]

罗绪
2023-03-14

我有这个程序,它几乎是一个计算器,但有一个移动的JLabel,每次你点击标签时都应该改变颜色,但我在代码的最底部有3个错误,我已经用注释标记了。所有三个都是:错误:不兼容类型:可能从长整型转换为整数

public class TestCalculator {
private ResultPane resultPane;


public static void main(String[] args) {
    new TestCalculator();
}

public TestCalculator() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                resultPane = new ResultPane();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            JFrame frame = new JFrame("Testing");
            frame.setGlassPane(resultPane);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new CalculatorPane(resultPane));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.setBounds(200,200,500,400);

        }
    });
}

public class ResultPane extends JPanel {

    private JLabel result;
    private Timer timer;

    private int xDelta = (Math.random() > 0.5) ? 1 : -1;
    private int yDelta = (Math.random() > 0.5) ? 1 : -1;
    public void setLabelForeground(Color color) {
        result.setForeground(color);
    }



    public ResultPane() {
        setOpaque(false);
        setLayout(null);
        result = new JLabel();
        Font font = result.getFont();
        font = font.deriveFont(Font.BOLD, 26f);
        result.setFont(font);
        add(result);
        HandlerClass handler = new HandlerClass();
        result.addMouseListener(handler);
        result.addMouseMotionListener(handler);
        timer = new Timer(40, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Point point = result.getLocation();
                point.x += xDelta;
                point.y += yDelta;
                if (point.x < 0) {
                    point.x = 0;
                    xDelta *= -1;
                } else if (point.x + result.getWidth() > getWidth()) {
                    point.x = getWidth() - result.getWidth();
                    xDelta *= -1;
                }
                if (point.y < 0) {
                    point.y = 0;
                    yDelta *= -1;
                } else if (point.y + result.getHeight() > getHeight()) {
                    point.y = getHeight() - result.getHeight();
                    yDelta *= -1;
                }
                result.setLocation(point);
                repaint();
            }

        });
        timer.start();
    }

    public void setResult(Number number) {
        result.setText(NumberFormat.getNumberInstance().format(number));
        result.setSize(result.getPreferredSize());
        setVisible(true);
    }
    public String getResultText() {
        return result.getText();
    }

}

public class CalculatorPane extends JPanel {

    private final ResultPane resultPane;

    private final JLabel firstNumberLabel = new JLabel("First Number:");
    private final JLabel secondNumberLabel = new JLabel("Second Number:");

    private final JTextField firstNumberField = new JTextField(5);
    private final JTextField secondNumberField = new JTextField(5);

    public double result = 0.0;

    public CalculatorPane(ResultPane resultPane) {

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        this.resultPane = resultPane;

        JPanel fields = new JPanel();
        fields.add(firstNumberLabel);
        fields.add(firstNumberField);
        fields.add(secondNumberLabel);
        fields.add(secondNumberField);

        add(fields, gbc);

        JPanel buttons = new JPanel();
        buttons.add(new JButton(new AddAction()));
        buttons.add(new JButton(new SubtractAction()));
        buttons.add(new JButton(new MultiplyAction()));
        buttons.add(new JButton(new DivideAction()));

        add(buttons, gbc);

    }

    public class AddAction extends AbstractAction {

        public AddAction() {
            putValue(NAME, "+");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 + num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class SubtractAction extends AbstractAction {

        public SubtractAction() {
            putValue(NAME, "-");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 - num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class MultiplyAction extends AbstractAction {

        public MultiplyAction() {
            putValue(NAME, "x");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 * num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class DivideAction extends AbstractAction {

        public DivideAction() {
            putValue(NAME, "/");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 / num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
                firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }
    }

}
private class HandlerClass implements MouseListener, MouseMotionListener {
        public void mouseClicked(MouseEvent event) {
        int r = Math.round(Math.random() * 255);//error here
    int g = Math.round(Math.random() * 255);//here
    int b = Math.round(Math.random() * 255);//and here
    Color col = new Color(r, g, b);
        resultPane.setLabelForeground(col);
        }
        public void mouseReleased(MouseEvent event) {
        }
        public void mousePressed(MouseEvent event) {
        }
        public void mouseExited(MouseEvent event) {
        }
        public void mouseEntered(MouseEvent event) {
        }
        public void mouseMoved(MouseEvent event) {
        }
        public void mouseDragged(MouseEvent event){
        }
    }



}

共有3个答案

景令秋
2023-03-14

Math.random() 为您提供了一个长整型,它可能远远超过整数可以表示的值的范围。然后,将该值分配给一个整数。

这就是编译器警告你的。

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

拓拔稳
2023-03-14

您试图通过将< code > long (< code > math . round 的结果)赋给< code>int,让编译器提供隐式基元收缩转换。它不能隐式地完成;使用强制转换显式完成。

int r = (int) Math.round(Math.random() * 255);
乜昆
2023-03-14

这是因为long是64位,int是32位,更不用说您要从浮点数变成整数。要从longint,您将不得不丢弃一些信息,而编译器不能/不会自动这样做。您必须通过强制转换明确说明:

int g = (int) Math.round(Math.random() * 255);
        ^^^^^

或者,您可以使用< code>java.util.Random:

Random r = new Random();
int g = r.nextInt(256);
 类似资料:
  • 我希望输入一个和另一个ex: 1和1000000000,现在我希望创建一个大小为1000000000的数组。然后在数组的每个索引处,存储int val,ex:。 当我尝试执行此操作时,Netbeans 会向我显示此行中的错误: “可能从long到int的有损转换”。这是我的密码:-

  • 问题内容: 我试图将long值传递给该方法,并在那里使用它来创建Long Array。但是,在创建数组时,出现“可能从long到int的有损转换”错误 尽管我还没有使用任何整数值。 问题答案: 数组维只能是类型。编译器期望使用该类型,但是您要传递一种类型。您可以更改传递给的参数类型,并进行相应的更改。 为了完整起见,这是JLS关于数组变量的内容 它们由使用非负 整数 索引值的数组访问表达式引用。

  • 我试图在一个数组(类型为long)中找到中间的索引我正在解决的问题特别要求返回一个long,所以我不能更改签名我想在我的quicksort代码中找到支点,但是我得到一个错误“可能有损于从long到int的转换”我知道在除法时我可能会丢失一些信息,但是我想绕过它下面是包含错误的代码:

  • 我试图在Textpad中复制这个Java程序,但我收到以下错误 C:\Users\User\Desktop\java\Drawing.java:14: 错误: 不兼容的类型: 从 float 到 int g.drawLine ((getWidth()/2) , 0, (getWidth()*i) , (getHeight()/2)); 这是代码 在getWidth*i之前我已经尝试过添加(floa

  • 我有一个“从int到byte的可能有损转换”错误的问题,但我没有在代码中将整数转换为byte。 这是笔记本课 我不知道为什么我会得到这个错误。有人能帮助我吗?谢谢你。