• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

java program for sawtooth pattern

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello folks,
i am new to java programming. Have a little trouble with this java program that displays sawtooth pattern. I used for loop and put drawString statements inside the loop and executed twice and got the desired output. But the problem is when i resize the applet window the sawtooth disappears. So obviously there is a problem and i couldn't fix it. Can anyone help me with this. I have a condition for my class and that is i should use loops for this program cause i tried doing with methods and invoking methods and works fine but with for loop it is screwy.
This is my code

import java.awt.*;
import java.applet.Applet;

public class Tooth extends Applet
{
private int x = 40;
private int y = 40;

public void paint(Graphics g)
{
for(int i = 0; i < 2; i++)
{
g.drawString("S", x, y);
y = y + 15;
g.drawString("SS", x, y);
y = y + 15;
g.drawString("SSS", x, y);
y = y + 15;
g.drawString("SSSS", x, y);
y = y + 15;
g.drawString("SSSSS", x, y);
y = y + 15;
}

}

}
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
x and y are member variables and get initialized only once, when the applet is created. The "paint" method changes their values. The second time "paint" is called, x and y aren't at their beginning values, but at the values where "paint" left them the first time. Therefore the drawing shows up offscreen where it's invisible.

The best solution would be to make x and y local variables declared inside "paint". Then they'd be initialized each time "paint" was called.
 
kanaka tam
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Ernest. I did that and now it works fine..
kanaka
 
In the renaissance, how big were the dinosaurs? Did you have tiny ads?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic