Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
bernie killed rosa
Feb 23, 2003
I'm working with probabilities and designing a network simulator that drops packets with probability p. I've never dealt with probabilities before in Java, and google wasn't of much help, so this is why I ask in this thread: How do I make sure stuff happens with probability p? I was thinking of having a double p, and using Math.random(), but I don't know exactly how to use these two things to come up with the answer.

Any help would be appreciated! Sorry if this is a really stupid question.

Adbot
ADBOT LOVES YOU

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

Marinol posted:

I'm working with probabilities and designing a network simulator that drops packets with probability p. I've never dealt with probabilities before in Java, and google wasn't of much help, so this is why I ask in this thread: How do I make sure stuff happens with probability p? I was thinking of having a double p, and using Math.random(), but I don't know exactly how to use these two things to come up with the answer.

Any help would be appreciated! Sorry if this is a really stupid question.

code:
if (Math.random() < p) {
  //event does happen
} else {
 //event doesn't happen
}

zootm
Aug 8, 2006

We used to be better friends.

Paolomania posted:

If you take a look at java.util.Arrays, this is exactly the kind of functionality that this class's static methods handle. The lack of shuffling functionality for primitives could be considered a hole in this class's functionality.
I did mention exactly that:

zootm posted:

There's no Arrays.shuffle for primitive arrays which seems like a particularly annoying omission; no idea what's going on there.

KuruMonkey posted:

So; the array of chars is a subclass of Object, but the chars in it aren't. And the function definition I was reading was actually wanting a collection of Object subclasses, not primitives.
Yes, basically char[] is not a subtype of Object[], but it is a subtype of Object. Because Arrays.asList() takes varargs (T...), the asList call is interpreted as an array of primitive arrays (a list with only one item, of course, which is your array).

I wouldn't worry too much about getting muddled up regarding this; the difference between primitives and Objects in Java is one which leads to a lot of weird inconsistencies in the language.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Elos: In addition to what Paolomania said, play around with rendering hints. In my case I'm often drawing something at a low resolution and upscaling at the end, so I've seen a large improvement in performance by doing something like this when appropriate:

code:
public void paint(Graphics g) {
	if (g instanceof Graphics2D) {
		Graphics2D gd = (Graphics2D) g;
		gd.setRenderingHint( RenderingHints.KEY_RENDERING,
		                     RenderingHints.VALUE_RENDER_SPEED);
		gd.setRenderingHint( RenderingHints.KEY_INTERPOLATION,
		                     RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
	}

	...
}
(Incidentally if this is actually a dumb idea, I'd appreciate somebody telling me why. There have been several times when I thought I had AWT all figured out only to discover later I was wrong.)

Elos
Jan 8, 2009

Paolomania posted:

So it looks like draw performance. A few things to try:

- look into whether or not the shared memory extension is turned on. If not, your application is doing extra buffer copies to the X server.

- use GraphicsConfiguration.getImageBufferCapabilities() to see if you have access to all the hardware acceleration that you think you do. Try turning off transparency to see if that one rendering option is the culprit.

- perhaps that image processing you are doing to create the alpha values is causing the JVM to treat your images as unaccelerated buffers that need to be kept both in the heap as well as in video RAM. You could maybe try some tricks to try to force the JVM to store your images in video RAM (see here).

I'm already using GraphicsConfiguration.createCompatibleImage for my images and I just tried emoving anything transparceny or alpha compositing related but still getting horrible performance. How can I find out wether shared memory extension is turned on?

getImageCapabilities().isAccelerated() returns false which I presume is a bad sing.

HFX
Nov 29, 2004

Elos posted:

I'm already using GraphicsConfiguration.createCompatibleImage for my images and I just tried emoving anything transparceny or alpha compositing related but still getting horrible performance. How can I find out wether shared memory extension is turned on?

getImageCapabilities().isAccelerated() returns false which I presume is a bad sing.

Yes it is. Think of a fresh Windows or X install when you are back on default SVGA drivers and everything takes forever to refresh.

Jo
Jan 24, 2005

:allears:
Soiled Meat

Elos posted:

That method just loops trough an array asking the tiles to draw themselves. I don't have any real reason for drawing it constantly besides wanting to see how it's done and hell, I might want to make it a pseudo-realtime like Diablo or something.

I'm doing all the transparency and color mask stuff before the gameloop so it just draws simple 16x16 images on the screen and checks for key events. There must be something strange going on in the linux JRE.

EDIT: Is there an easy way to find out which method is hogging all the CPU?

We're working on VERY similar projects. I had the same problem and realized that the CPU consumption was perfectly fine -- just that I wasn't telling the draw thread to wait and allow the input function to run, which made everything feel very laggy.

Catch me on aim (MostlyDeadAllDay) or send me a PM. We may have a lot of overlap.

Jo
Jan 24, 2005

:allears:
Soiled Meat
A tangentially related note: I'm allocating hardware memory and have an alpha-transparent png loaded as below:

code:
	BufferedImage tempTileset = ImageIO.read( new File( tilesetFullPath ) );
	tileset = engine.gfxman.getHardwareMemoryChunk( tempTileset.getWidth(), tempTileset.getHeight() );
	tileset.getGraphics().drawImage( tempTileset, 0, 0, null );
Problem is when doing the 'drawImage' command, I lose all the alpha data. What's the best way to copy over the tempTileset, taking format conversion into account? I've tried tempData.copyData and tempData.setData, but would like to know the correct way of doing this.

EDIT: I swear to god I spend hours on these things only to solve them moments after I ask for help. I loving hate that. Problem was in getHardwareMemoryChunk, which had a wrong value for transparency. drawImage works fine.

Least it works now.

Jo fucked around with this message at 20:06 on Oct 24, 2010

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Jo: Spiffy. Is that lighting baked into your maps, or calculated on the fly? I think your perspective is slightly off. If those walls are one square high, this shadow line should be moved down, so the shadow begins where the back of that wall would touch the ground:

Paolomania
Apr 26, 2006

Elos posted:

getImageCapabilities().isAccelerated() returns false which I presume is a bad sing.

Big question: which linux Java compiler and JVM are you using? I have had issues with gcj, which is the default Java on Debian/Ubuntu, missing functionality.

Paolomania
Apr 26, 2006

OpenJDK also looks like it had alot of closed-source native code removed from the graphics libraries. You might have to try the Oracle JRE to see if that makes a difference.

magicalblender
Sep 29, 2007
Is it possible to make a decorator class that doesn't call super() on its superclass?

Example code
I have a class Widget, which I can't modify the source code to. I want to know when methods frob() and troz() get called, so I make a decorator NoisyWidget, which alerts me when they get called. I instantiate a NoisyWidget and pass it to a function that takes Widgets.

I expect the output to be this:
code:
Doing lots of work...
function frob was called!
function troz was called!
but I get this:
code:
Doing lots of work...
Doing lots of work...
function frob was called!
function troz was called!
It looks like Java is inserting an implicit super call in the NoisyWidget constructor. This is causing it to do 100% more work than it needs to. Is there any way to tell Java, "no thanks, I really don't want to call super(), implicitly or otherwise"?

I suspect this post might be an XY problem, so I'll also ask a higher-level question. I want to monitor Widget's methods - how else can I do this?

Sereri
Sep 30, 2008

awwwrigami

magicalblender posted:

Is it possible to make a decorator class that doesn't call super() on its superclass?

The way Java works with classes is to call super() all the way up to Object. Even stand-alone classes are basically '(public) class Yadda extends Object'. You can write the super() yourself or not but it will always be there. Sorry dude.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
If you have control over when Widgets are constructed, then you only need to give NoisyWidget constructors with the same signatures as Widget's constructors and have them call the appropriate supers.
code:
public NoisyWidget(){
  super();
}

public NoisyWidget(xxx){
  super(xxx);
}
// ...
Widget root = new NoisyWidget();
edit: If you just want a frequency count, use a profiler.

Mustach fucked around with this message at 16:39 on Oct 25, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
That's one reason why composition is better than inheritance.

In order to answer your general question, what kind of monitoring do you need to perform?

magicalblender
Sep 29, 2007

TRex EaterofCars posted:

In order to answer your general question, what kind of monitoring do you need to perform?

Widget is actually a PacketHandler class, and the methods I'm interested in are actually
code:
void receive(PacketTypeA p);
void receive(PacketTypeB p);
void receive(PacketTypeC p);
//etc. 
One kind of packet handles chat messages, and I want to record those messages in a log file. So essentially, I wanted to do this;

code:
public class NoisyPacketHandler{
 void receive(PacketTypeC p){
  log("message from user " + p.sender + ": " + p.message);
  parent.receive(p);
 }
}

hayden.
Sep 11, 2007

here's a goat on a pig or something
I'm taking an intro Java course and wanted to play around with using a MySQL database with Java. I have a shared hosting (Lithium Hosting if it matters) and I setup a MySQL database/table.

What url would I actually use to connect to this? Some variation of jdbc:mysql://somedomain.com? Are there any particular settings I need to change for this to work? Am I retarded?

Here's the code I found online I was trying to use:

code:
           Connection conn = null;

           try
           {
               String userName = "user";
               String password = "password";
               String url = "jdbc:mysql://somedomain.com";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");
           }

hayden. fucked around with this message at 00:09 on Oct 26, 2010

chippy
Aug 16, 2006

OK I DON'T GET IT
That should do it. Set up a user account via whatever you're using to admin your database, use the login details for that for userName and password and the url will be, as you said, jdbc:mysql://yourdomainhere.com. You'll need to install the MySQL Connector (http://www.mysql.com/products/connector/) and install it/add it to your build path as well. If you're using Eclipse you can do it from within that. What's happening when you try to run it?

chippy fucked around with this message at 00:20 on Oct 26, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

magicalblender posted:

Widget is actually a PacketHandler class, and the methods I'm interested in are actually
code:
void receive(PacketTypeA p);
void receive(PacketTypeB p);
void receive(PacketTypeC p);
//etc. 
One kind of packet handles chat messages, and I want to record those messages in a log file. So essentially, I wanted to do this;

code:
public class NoisyPacketHandler{
 void receive(PacketTypeC p){
  log("message from user " + p.sender + ": " + p.message);
  parent.receive(p);
 }
}

Why bother passing in the Widget to decorate with NoisyWidget then? Just allow Java to call the super() for you in the default constructor and do nothing.

hayden.
Sep 11, 2007

here's a goat on a pig or something

chippy posted:

That should do it. Set up a user account via whatever you're using to admin your database, use the login details for that for userName and password and the url will be, as you said, jdbc:mysql://yourdomainhere.com. You'll need to install the MySQL Connector (http://www.mysql.com/products/connector/) and install it/add it to your build path as well. If you're using Eclipse you can do it from within that. What's happening when you try to run it?

I think I got it figured out from this, thanks a ton :)

If anyone has some websites/resources that explain why I need the MySQL Connector, I'd appreciate it. I don't really understand how all this stuff interacts.

hayden. fucked around with this message at 00:53 on Oct 26, 2010

chippy
Aug 16, 2006

OK I DON'T GET IT
I think I followed these instructions: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.birt.doc/birt/connecting.2.4.html after downloading the connector from the page I linked above.

If you start by specifically catching the difference exceptions it can throw instead of just Exception then you can start to work out where the problem is. That block can throw ClassNotFoundException, IllegalAccessException, InstantiationException or SQLException. Handle these individually and print output indicating which one it is. It's probably ClassNotFoundException if you haven't added the connector yet.

edit: Oh you worked it out, nice one.

chippy fucked around with this message at 01:03 on Oct 26, 2010

Jo
Jan 24, 2005

:allears:
Soiled Meat

Internet Janitor posted:

Jo: Spiffy. Is that lighting baked into your maps, or calculated on the fly? I think your perspective is slightly off. If those walls are one square high, this shadow line should be moved down, so the shadow begins where the back of that wall would touch the ground:



It's baked. In another version of this code it is all realtime with dynamic shadows and penumbras, but that's a mess and not worth diving into again.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Got a problem.
I'm trying to grab the videocard name (in Windows) by executing dxdiag then reading the log file.

But:
code:
File report = File.createTempFile("dxdiag", ".txt");
ProcessBuilder procbuild = new ProcessBuilder("dxdiag", "/t", report.toString());
Process proc = procbuild.start();
proc.waitFor()
pastebin of incomplete code
The process returns 0 immediately because dxdiag spawns a new process to do all its processing, which takes a few seconds. How do I reliably wait until the log file is written before trying to read it? (Is it possible?)

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Aleksei Vasiliev posted:

Got a problem.
I'm trying to grab the videocard name (in Windows) by executing dxdiag then reading the log file.

But:
code:
File report = File.createTempFile("dxdiag", ".txt");
ProcessBuilder procbuild = new ProcessBuilder("dxdiag", "/t", report.toString());
Process proc = procbuild.start();
proc.waitFor()
pastebin of incomplete code
The process returns 0 immediately because dxdiag spawns a new process to do all its processing, which takes a few seconds. How do I reliably wait until the log file is written before trying to read it? (Is it possible?)

You can spin. Basically a thread with a sleep() in it and a timeout in case the file never gets produced.

Paolomania
Apr 26, 2006

Since the additional process fork leaves you with no connection to the process that actually does the work there is no way to get a notification of its exit from within Java. You would have to just wait a reasonable amount of time or poll the file status (which also involves waiting). Since you know that this is Windows-specific I would wrap the call to dxdiag in a shell script and run (and wait on) the script from Java instead.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Paolomania posted:

Since the additional process fork leaves you with no connection to the process that actually does the work there is no way to get a notification of its exit from within Java. You would have to just wait a reasonable amount of time or poll the file status (which also involves waiting). Since you know that this is Windows-specific I would wrap the call to dxdiag in a shell script and run (and wait on) the script from Java instead.
Okay, what's different between cmd and a batch file? Running dxdiag from cmd returns immediately, just like Java, but a batch file waits for it to finish. why are batch files magic

TRex EaterofCars posted:

You can spin. Basically a thread with a sleep() in it and a timeout in case the file never gets produced.
What happens if it wakes up while the file is being written (since it now exists) and starts reading?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Aleksei Vasiliev posted:

Okay, what's different between cmd and a batch file? Running dxdiag from cmd returns immediately, just like Java, but a batch file waits for it to finish. why are batch files magic
What happens if it wakes up while the file is being written (since it now exists) and starts reading?

Check file sizes between poll intervals. If it doesn't change, read.

Paolomania
Apr 26, 2006

Aleksei Vasiliev posted:

Okay, what's different between cmd and a batch file? Running dxdiag from cmd returns immediately, just like Java, but a batch file waits for it to finish. why are batch files magic

http://blogs.msdn.com/b/powershell/archive/2007/01/16/managing-processes-in-powershell.aspx

My guess is it has something to do with automatic piping.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Paolomania posted:

http://blogs.msdn.com/b/powershell/archive/2007/01/16/managing-processes-in-powershell.aspx

My guess is it has something to do with automatic piping.

quote:

But what if I do want to wait for the Win32 process? In cmd.exe, you'd do this with "start /wait" but this command is not (directly) available in PowerShell. So what do we do?
This made me happy until it turned out to only work in cmd with Java throwing a file-not-found on "start".

Oh well, guess I'm stuck with polling.
Thanks yall

edit: NEW QUESTION!

Using this works:
ProcessBuilder procbuild = new ProcessBuilder("cmd", "/c", "start/wait", "dxdiag", "/64bit", "/t", report.toString() );

But only if I use "/64bit" on a x64 system, or don't on a 32-bit. JVM bitness doesn't matter. (Fun DXDiag fact! If you don't use /64bit when running dxdiag on an x64 system it will run normally, spend a few seconds getting all the info, then terminate without writing it.)
So now I just need to figure out how to get processor bitness in Java :suicide:

Malloc Voidstar fucked around with this message at 18:00 on Oct 26, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Is there a package that might get this info for you already made?

If not, I would recommend using C/C++/anything else to do this work and then running THAT from java.

Paolomania
Apr 26, 2006

Yeah, if what you are trying to do is so windows-graphics-specific, why are you trying to do it in a Java app?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Paolomania posted:

Yeah, if what you are trying to do is so windows-graphics-specific, why are you trying to do it in a Java app?
I only know Java, this project isn't important enough to learn a new language (it's a tiny program for Fallout: New Vegas), and this isn't an essential part of the program. It's just convenient.

Here's all my terrible videocard detection code if anybody wants it for some reason: http://pastebin.com/SGDKvh5U

edit: vbscript is better than java http://pastebin.com/m9QXjyeh

Malloc Voidstar fucked around with this message at 09:04 on Oct 27, 2010

Revitalized
Sep 13, 2007

A free custom title is a free custom title

Lipstick Apathy
So I'm reviewing my notes for my midterm tomorrow, and I noticed I'm missing something.

What are the pros and cons of Singly Linked Lists and Doubly Linked Lists?

As far as Arrays and LinkedLists go, I know there's a difference in memory space usage, but as far as Singly and Doubly linked list, I'm not sure what's the drawback on a doubly as opposed to a singly. Is there one?

baquerd
Jul 2, 2007

by FactsAreUseless

Revitalized posted:

So I'm reviewing my notes for my midterm tomorrow, and I noticed I'm missing something.

What are the pros and cons of Singly Linked Lists and Doubly Linked Lists?

As far as Arrays and LinkedLists go, I know there's a difference in memory space usage, but as far as Singly and Doubly linked list, I'm not sure what's the drawback on a doubly as opposed to a singly. Is there one?

A singly linked list uses half of the memory to store its links, and will generally be a lighter weight component with fewer supported operations. It's a potential data structure for use in embedded systems with extremely low memory, but in modern programming it is not practically used.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Despite the apparent consensus of this thread, optimizing your memory use is still practically useful, even on modern hardware; using less memory improves locality, allows less frequent GCs, and in many applications permits more instances of your code to be run in parallel and/or more data to be kept in in-memory cache.

Anyway, the side of linked lists that you don't necessarily hear about in intro classes is that usually the most practical linked lists are "invasive": instead of having a bunch of link objects with pointers to data objects, they keep their previous and next pointers in the data objects themselves (which of course means that the object can only be in one list at once). Not only does this cut the memory overhead of the list by well over half, but it makes it very efficient to manipulate the list given only references to data objects. Unfortunately, Java makes these very difficult to implement in a library unless you don't need a particular base class, which is part of why it's good to practice your linked-list algorithms in the first place. :)

Java's LinkedList is almost completely worthless, not because it's a bad implementation, but because linked lists are rarely the right data structure for the problem, and when they are, you usually want an invasive list.

baquerd
Jul 2, 2007

by FactsAreUseless
http://download.oracle.com/javaee/6/api/javax/persistence/OneToMany.html

code:
    Example 3: Unidirectional One-to-Many association using a foreign key mapping

    // In Customer class:
    @OneToMany(orphanRemoval=true)
    @JoinColumn(name="CUST_ID") // join column is in table for Order
    public Set<Order> getOrders() {return orders;}
This is how a lot of people say to do this relationship in JPA 2.0.

Why then, does only the following work (all attributes are required):

code:
@OneToMany(cascade= {CascadeType.ALL}, targetEntity=Orders.class)    
public Set<Order> getOrders() {return orders;}
If I remove the cascade, the entity, or add in @JoinColumn, it crashes and burns. As it is here, it works exactly as unit tests expect. The unit tests are assumed to be good. Does anyone have any idea what the hell?

Max Facetime
Apr 18, 2009

baquerd posted:

Does anyone have any idea what the hell?

Maybe it's just your JPA Provider. Which one do you use?

Crystilastamous
Sep 16, 2007
Corp Por *Throws Phone Book*
Hail Cobolians! Is that the correct vernacular? Let's get down to business though,
this a partially finished assignment, dealing with printing squares, and two different types of triangles. I was wondering if anyone could help me debug the drawUpperTriangle method. Because of the stipulations the professor has put on it, I'm having trouble making it work, and I've read a lot of tutorials dealing with nested loops etc. I figured some goon help might help. Don't laugh at me, I'm still learning.




code:
import java.util.Scanner;


public class Boxes
{
	public static void main ( String [] args )
	{
		String line = "";
		char topBottom = '-';
		String shapeInput = "";
		String shape;
		String triangleType = "";
		String upperOrLower = "";
		String isSquare = "S";
		String isTriangle = "T";
		String upper = "U";
		String lower = "L";
		
		Scanner scanInput = new Scanner ( System.in );
		
		String fillCharacter = "";
		String fillChar = "";
		int boxSize;
		
		System.out.print ( "Please enter the fill character: " );
		fillCharacter = scanInput.next();
		fillChar = fillCharacter.substring(0,1);
		
		System.out.print ( "Please enter the size of the box (0 to 80): ");
		boxSize = scanInput.nextInt();
		
		while (boxSize < 0 || boxSize > 80)
		{
			boxSize = 0;
			System.out.print ( "Please enter the size of the box (0 to 80): ");
			boxSize = scanInput.nextInt();
		}
		
		shape = getShape();
		
		int i;
		
		for ( i = 0 ; i < boxSize ; i++ )
		{
				line += topBottom;
		}
		
		System.out.println ('+' + line + '+'); // top of box
		
		if (shape.equals("S"))
		drawSquare(fillChar, boxSize);
		if (shape.equals("U"))
		drawUpperTriangle(fillChar, boxSize);
		
		
		System.out.println ('+' + line + '+'); // top of box
		
		
		
	} // end of main method
	
	
	public static String getShape()
	{
	
		String shapeInput = "";
		String shape = "";
		String triangleType = "";
		String upperOrLower = "";
		String isSquare = "S";
		String isTriangle = "T";
		String upper = "U";
		String lower = "L";
		
		Scanner scanInput = new Scanner ( System.in );
		
			
		System.out.print ("Square or triangle in the box? (S or T): ");
		shapeInput = scanInput.next();
		shape = shapeInput.substring(0,1);
		
		
		
		while ( !shape.equalsIgnoreCase(isSquare) && !shape.equalsIgnoreCase(isTriangle) )
		{
			
			System.out.print ("Square or triangle in the box? (S or T): ");
			shapeInput = scanInput.next();
			shape = shapeInput.substring(0,1);
		}
		
		if (shape.equalsIgnoreCase(isTriangle))
		{
		
			System.out.print ("Upper or lower triangle (U or L): ");
			upperOrLower = scanInput.next();
			triangleType = upperOrLower.substring(0,1);
			
			while (!triangleType.equalsIgnoreCase(upper) && !triangleType.equalsIgnoreCase(lower))
			{
				System.out.print ("Upper or lower triangle (U or L): ");
				upperOrLower = scanInput.next();
				triangleType = upperOrLower.substring(0,1);
			}
			
		}
		
		if (triangleType.equalsIgnoreCase(upper))
			shape = upper;
			
		if (triangleType.equalsIgnoreCase(lower))
			shape = lower;
		
		if (shape.equalsIgnoreCase(isSquare))
			shape = isSquare;
		
		return shape;
		
		
			
	} // end of getShape method
	
	public static void drawSquare(String fillChar, int boxSize)
	{
		String boxFiller = "";
		
		int i;
		
		String fillChar2 = fillChar;
		int boxSize2 = boxSize;
		
		for ( i = 0 ; i < boxSize2 ; i++ )
		{
			boxFiller += fillChar2;
		}
		
		for ( i = 0 ; i < boxSize2 ; i++ )
		{
			System.out.println('|' + boxFiller + '|');
		}

		
	} // end of drawSquare method
	
	public static void drawUpperTriangle(String fillChar, int boxSize)
	{
		String boxFiller = "";
		String space = " ";
		String remove;
		
		
		
		String fillChar2 = fillChar;
		int boxSize2 = boxSize;
		int i;
		int j;
		int k;	
		
		for ( i = 0 ; i < boxSize2 ; i++ )
		{
			boxFiller += fillChar2;
		}
		
		
		for ( i = 0 ; i < boxSize2 ; i++ )
		{
			System.out.println('|' + boxFiller + '|');			
		}



		

					
	} // end of drawUpperTriangle method
	
} // end of class Boxes



rogram: Boxes
Name your program: Boxes.java.
The program will draw a square or one of two triangles. The square or triangle will be enclosed in a box. The box will be made of -’s across the top and bottom, |’s on the two sides, and +’s in the four corners. See the examples section.
The Boxes.java program will ask the user for:

1.
•A character that will be used as the fill character. If the user enters more than one character, use the first character.
2.
•An integer that is the size of the box. The size must be in the range 0 to 80.
3.
•A character that will be either 'S' or 's' to draw a filled-in square, or will be either 'T' or 't' to draw a triangle.
4.
•If the user want a triangle, ask the user if they want an upper triangle, 'U' or 'u', or a lower triangle, 'L' or 'l'.

At this point, look through the next section to get a feel for what the program is supposed to draw. Then, read the last section that talks about the methods you are to include in your solution.
Examples:
Example A, drawing a Square:
Please enter the fill character: z
Please enter the size of the box (0 to 80): 3
Square or Triangle in the box? (S or T): S
+---+
|zzz|
|zzz|
|zzz|
+---+
Example B, drawing a Square:
Please enter the fill character: 836,095.abc
Please enter the size of the box (0 to 80): 5
Square or Triangle in the box? (S or T): s
+-----+
|88888|
|88888|
|88888|
|88888|
|88888|
+-----+
Example C, drawing an upper triangle:
Please enter the fill character: ;
Please enter the size of the box (0 to 80): -3
Please enter the size of the box (0 to 80): 87
Please enter the size of the box (0 to 80): 6
Square or Triangle in the box? (S or T): T
Upper or lower triangle? (U or L): u
+------+
|;;;;;;|
|;;;;; |
|;;;; |
|;;; |
|;; |
|; |
+------+
Example D, drawing a lower triangle:
Please enter the fill character: %
Please enter the size of the box (0 to 80): 5
Square or Triangle in the box? (S or T): t
Upper or lower triangle? (U or L): s
Upper or lower triangle? (U or L): z
Upper or lower triangle? (U or L): R
Upper or lower triangle? (U or L): L
+-----+
| %|
| %%|
| %%%|
| %%%%|
|%%%%%|
+-----+
Example E, drawing a figure with size set to 0:
Please enter the fill character: &
Please enter the size of the box (0 to 80): 0
Square or Triangle in the box? (S or T): T
Upper or lower triangle? (U or L): L
++
++
Required Methods:
Your solution will have five methods: main, getShape, drawSquare, drawLowerTriangle, and drawUpperTriangle.
The getShape method will ask the user what shape to draw: square or triangle. If the user selects triangle, the method will then ask if the user wants an upper or lower triangle. See the examples above. getShape will keep repeating questions until the user enters a correct answer. The method will return a char that will be one of: 'S', 's', 'U', 'u', 'L', 'l'.
The drawSquare method will draw the square with the left and right borders. It will not draw the top or bottom line (that will be done by main).
The drawLowerTriangle method will draw the lower triangle. It will not draw the top or bottom lines. The drawUpperTriangle method is similar.
The three draw methods will not return anything.

Keyboard Kid
Sep 12, 2006

If you stay here too long, you'll end up frying your brain. Yes, you will. No, you will...not. Yesno, you will won't.
I started learning Java recently, so I'm relatively new to it.

I need to take an ArrayList<String>, let's call it al1, and then make a second ArrayList<String>, al2, that contains all the unique elements from al1. Unique does not include case, so if I have:

al1: "a" "b" "c" "A" "B" "C" "D"
I want to end up with:
al2: "a" "b" "c" "D"
Or something similar. This also needs to work with words, so I can't just use char methods.

I know that String has a equalsIgnoreCase method, but I don't know how to use it when adding elements.

Let's say I've got
code:
        for( String word : al1 )
        {
            if( !al2.contains(word))
            al2.add(word);
        }
But now I need to incorporate ignoring the case of the Strings.

I tried incorporating an Iterator to remove the copies, but I couldn't get it to work. Is there a simpler way that I'm just missing?

Adbot
ADBOT LOVES YOU

Sereri
Sep 30, 2008

awwwrigami

Keyboard Kid posted:

:words:

code:
        for( String word : al1 )
        {
            if( !al2.contains(word.toUpperCase))
            al2.add(word.toUpperCase);
        }
Like that ?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply