-2

I'm trying to copile this Java program in Textpad, but I'm getting the following error

C:\Users\User\Desktop\java\Drawing.java:14: error: incompatible types: possible lossy conversion from float to int g.drawLine ((getWidth()/2) , 0, (getWidth()*i) , (getHeight()/2));

Here is the code

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Drawing extends JPanel
{
    public void painComponent(Graphics g)
    {
        super.paintComponent (g);
        for (float i=0; i<=1; i+=1/7)
        {
            Random r=new Random();
            g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            g.drawLine ((getWidth()/2) , 0, (getWidth()*i) , (getHeight()/2));
        }
        g.drawLine(0,getHeight()/2, getWidth()/2, getHeight()/2);
        g.drawLine(getWidth(), getHeight()/2, getWidth()/2, getHeight());
    }  

    public static void main(String args[])
    {
        Drawing d=new Drawing();
        JFrame frame=new JFrame();
        frame.add(d);
        frame.setSize(600,600);
        frame.setTitle("Drawing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

I've tried adding (float) to before getWidth*i, but it didn't work for me. Google wasn't of much help either, that or I haven't searched enough. I'd be very grateful if anyone could provide me with a certain solution.

Thank you

JMG
  • 5
  • 1
  • 1
    What on Earth are you doing iterating over floats? Your loop *may* not get over 1. – Makoto Nov 07 '17 at 23:06
  • Note that `i+=1/7` introduces **integer division**, `1/7` is thus `0` (**rounded** to next integer towards *zero*). You should use `1.0/7.0` or something similar instead. – Zabuzard Nov 07 '17 at 23:21
  • Side note: it’s a good idea to use `@Override` on methods you are overriding, precisely because it allows the compiler to catch misspellings like `public void painComponent`. As long as your method is spelled that way, it will never be called. – VGR Nov 08 '17 at 01:55

1 Answers1

1

Roughly speaking the compiler is claim because you are trying to make a narrow conversion without a cast. See this link.

The method

drawLine(int x1, int y1, int x2, int y2)

expects 4 int's as parameters but you are providing a float number as the 3rd parameter because

(getWidth()*i)

is a multiplication of an int and a float (the i variable) which results a float number (it is called as promotion, see the link above).

There are several ways to solve this issue but since your code have several other problems (like i+=1/7) the best thing to do here is try to learn a bit more about the java basis, like follow here.

Duloren
  • 2,395
  • 1
  • 25
  • 36