UPSB v4

Off-topic / Java Programming

  1. Mike
    Date: Sat, Aug 27 2011 06:18:33

    So, now I'm taking Java programming, and I was wondering if I could get some help. Now, I know Java is used for web-content most of the time, in the form of applets. Let's say I had the following application: [CODE] /* Program Description: Program that takes two integers * from a user and adds them, then displays the result */ public class Addition { public static void main(String[]args) { Scanner input = new Scanner(System.in); int number1; int number2; int sum; System.out.print("Enter first integer: "); number1 = input.nextInt(); System.out.print("Enter second integer: "); number2 = input.nextInt(); sum = number1 + number2; System.out.printf("Sum is %d\n",sum); } }[/CODE] How would I turn this application into an applet?

  2. UEDan
    Date: Sat, Aug 27 2011 08:00:53

    You toss out that code and re write it in some kind of C then compile, here it is in C# [CODE]using System; public class Addition { public static void Main() { string inputString; double number1; double number2; double sum; Console.Write("Enter first integer: "); inputString = Console.ReadLine(); number1 = Convert.ToDouble(inputString); Console.Write("Enter second integer: "); inputString = Console.ReadLine(); number2 = Convert.ToDouble(inputString); sum = number1 + number2; Console.Write("Sum is " + sum); } }[/CODE] =P

  3. strat1227
    Date: Sat, Aug 27 2011 15:29:56

    +10 million for mr dude.

  4. Mike
    Date: Sat, Aug 27 2011 17:26:50

    UEDan wrote: You toss out that code and re write it in some kind of C then compile, here it is in C# [CODE]using System; public class Addition { public static void Main() { string inputString; double number1; double number2; double sum; Console.Write("Enter first integer: "); inputString = Console.ReadLine(); number1 = Convert.ToDouble(inputString); Console.Write("Enter second integer: "); inputString = Console.ReadLine(); number2 = Convert.ToDouble(inputString); sum = number1 + number2; Console.Write("Sum is (0)", sum); } }[/CODE] =P
    Wait, but what if I want the applet to be written in Java? Writing it in C doesn't make a difference?

  5. Light
    Date: Sun, Aug 28 2011 19:12:26

    @Mike, I tried running that code, it doesnt even run..

  6. Mike
    Date: Sun, Aug 28 2011 22:54:37

    Light wrote: @Mike, I tried running that code, it doesnt even run..
    Runs perfectly fine on my computer. Sent from my SGH-T959 using Tapatalk

  7. Mike
    Date: Mon, Oct 31 2011 06:17:12

    I'm trying to write a program that will generate a random sentence using a random number generator. I have four arrays of strings and the program is supposed to generate at least 20 sentences. I need some help on my random number generator. @UEDan [CODE]import java.applet.Applet; import java.awt.Graphics; import java.util.Random; public class Strings extends Applet{ Random integer = new Random(); String article [] = {"the","a","one","some","any"}; String noun [] = {"boy","girl","dog","town","car"}; String verb [] = {"drove","jumped","ran","walked","skipped"}; String preposition [] = {"to","from","over","under","on"}; public void Paint (Graphics g){ int x = 20, y = 40;{ for (int i=0; i>20; i++){ g.drawString(generateSentence(), x, y+=15); } } } public int numberGenerator(){ int start = 0; for(int count = 0; count<=4; count++){ start= integer.nextInt()-1; } return start; } String generateSentence(){ String sentence = article[numberGenerator()] + "" + noun[numberGenerator()] + "."; return (sentence = sentence.substring(1).toUpperCase()); } }[/CODE]

  8. Timbo
    Date: Mon, Oct 31 2011 11:48:13

    It's been a fairly long time since I've used Java, but it's coming back to me now ;). Something that is more nitpicking than anything, don't call your variables things like 'integer'. Give more descriptive names. You seem to have your ideas about functions confused. The loop inside your numberGenerator function does nothing. I'm not sure why you're adding the empty string ("") into the sentence, maybe this was just a copy/paste error. In C this would serve as an end of string indicator, not sure if it's the same as in Java. Not quite sure why in your final line you are returning the entire string, bar the first character, in uppercase. (Remember indexes start at 0) Finally, your number generator is returning values outside of the bounds of your string arrays. You can use the modulus operator to prevent this from happening. On a side note, your indentation needs work as well, but that might just be copy/paste differences. EDIT: I may seem harsh but this is how help is given without giving answers, which is how it is done on any programming forum on the net. Also, it helps A LOT if you ask specific questions about things you don't understand rather than just posting a pile of code.

  9. Zombo
    Date: Mon, Oct 31 2011 14:53:04

    ur numberGenerator method does useless work, it goes through a loop, reassigns a random value to star 4 times. whats the point? only last random value will be used generateSentence does not generate complete sentences, ur only using article and noun, ull get something like "thecat.". oh and nextInt gives a random number between 0 and infinity basically if you want only between 0 and 3 u use nextInt(4)

  10. Mike
    Date: Wed, Nov 2 2011 06:38:51

    Timbo;147149]It's been a fairly long time since I've used Java, but it's coming back to me now ;). Something that is more nitpicking than anything, don't call your variables things like 'integer'. Give more descriptive names. You seem to have your ideas about functions confused. The loop inside your numberGenerator function does nothing. I'm not sure why you're adding the empty string ("") into the sentence, maybe this was just a copy/paste error. In C this would serve as an end of string indicator, not sure if it's the same as in Java. Not quite sure why in your final line you are returning the entire string, bar the first character, in uppercase. (Remember indexes start at 0) Finally, your number generator is returning values outside of the bounds of your string arrays. You can use the modulus operator to prevent this from happening. On a side note, your indentation needs work as well, but that might just be copy/paste differences. EDIT: I may seem harsh but this is how help is given without giving answers, which is how it is done on any programming forum on the net. Also, it helps A LOT if you ask specific questions about things you don't understand rather than just posting a pile of code.[/QUOTE] @Timbo Yes, I realize now that the loop does nothing. But I can't seem to figure out how to write that piece of code for some reason. The "" would mark a space in between the strings. Without them, thesentencewouldjustlooklikethis. The entire string is supposed to be returned to display a sentence, with the first character being upper-cased. And yeah, The loop is what I'm having a problem with currently. Be as harsh as you want, it will actually help me. [QUOTE=Zombo wrote: ur numberGenerator method does useless work, it goes through a loop, reassigns a random value to star 4 times. whats the point? only last random value will be used generateSentence does not generate complete sentences, ur only using article and noun, ull get something like "thecat.". oh and nextInt gives a random number between 0 and infinity basically if you want only between 0 and 3 u use nextInt(4)
    Yeah, I realized that I need to add the rest of the arrays to make a complete sentence, ha ha. I'm currently rewriting it at the moment, and I'm going to see if I can get it to run. Thanks for the help too, I appreciate it.

  11. Tkal
    Date: Wed, Nov 2 2011 19:21:05

    Mike wrote: The "" would mark a space in between the strings. Without them, thesentencewouldjustlooklikethis.
    No it doesn't lol. It would still give you asentencethatlookslikethis Replace "" with " " and you've got yourself a winnar.

  12. Mike
    Date: Thu, Nov 3 2011 01:55:26

    Tkal wrote: No it doesn't lol. It would still give you asentencethatlookslikethis Replace "" with " " and you've got yourself a winnar.
    Yes. That's what I meant.

  13. Tkal
    Date: Thu, Nov 3 2011 03:31:50

    See what I don't understand is why at all you have a separate method for generating a random number. Within your generateSentence method, you can just call random in the array index like article[integer.nextInt(4)]. Java will automatically evaluate the argument and then access that element in the array. (nextInt(4) should generate numbers from 0 to 3). numberGenerator is pretty pointless. And in the case that your arrays of nouns, articles, and whatnot are variable in size, you could just pass the size of each array to generateSentence and then have article[integer.nextInt(numArticle)].

  14. Timbo
    Date: Thu, Nov 3 2011 05:19:12

    Often these types of assignments have a list of methods that you have to implement. Even still there is nothing wrong with adding a layer of abstraction especially in a project as simple as this. Mike, I meant what Tkal said with the "" issue, it's been cleared now anyway. If the loop does nothing, get rid of it. Like people have been saying, all that you need to generate a random number is integer.nextInt(4). If you return that value from your method then hey presto. I'm not even sure why you're using the string.substring method at all. You don't want a substring of the sentence you want the whole thing. toUpper converts and entire string to uppercase, not just the first character. The only two problems really lie in your numberGenerator method (easily resolved) and the return statement of your generateSentence method.

  15. Tkal
    Date: Thu, Nov 3 2011 12:24:14

    There might be nothing wrong with an additional layer of abstraction, but if it doesn't really help the readability or efficiency of the program then I have a little bit of trouble justifying a whole other method. Of course you could also be correct that the assignment might require that Mike create functions to perform certain aspects. To fix the string output, simply take the string, do .charAt(0).toUpperCase() (which takes the first character of the character array and turns it into an uppercase) and then output the rest of the string using the substring call that already exists, only without the toUpperCase() call. For future reference, it would also help to post exactly what your current output is, if it works at all.

  16. Timbo
    Date: Thu, Nov 3 2011 14:32:00

    On a side note, does anyone else think that Java is a cool language with a bad implementation? I don't mean the actual implementation is poorly done, just that I don't really like the idea of the implementation.

  17. Tkal
    Date: Thu, Nov 3 2011 15:13:22

    What about the implementation do you think is off putting? I know a lot of people say this and I'm still trying to formulate my own opinion on the matter, but I don't have enough experience with coding (only know C/C++ and Java) to really make up my mind. The crossplatform functionality with the JVM is definitely why people use it though.

  18. Zombo
    Date: Thu, Nov 3 2011 16:58:40

    Timbo wrote: I don't mean the actual implementation is poorly done, just that I don't really like the idea of the implementation.
    wtf does this sentence mean? are you talking about interfaces??

  19. Timbo
    Date: Thu, Nov 3 2011 17:10:44

    No, I'm talking about how the language is run in the JVM. If there is a better way to say this than 'How the language is implemented' then I don't know it. I myself am no expert in programming languages either (especially Java) so I realise my opinion holds little to no weight. In fact I'm only giving my opinion to further discussion, not to try and actually convince anyone of anything. I know the benefits of the JVM but coming from a C background it feels wrong to take a pure language like what Java seems to be (I gather this from the fact that classes can only inherit from one class, interfaces instead of abstract virtual classes, correct me if I'm wrong) and then make it slower and less-pure by adding a layer between it and the CPU. I do know that this opinion is more based on ideals than anything else, and the benefits far outweigh whatever (if any) negatives that I have presented here. Also, I'm pretty much just outright expecting an adverse reaction from Zombo about how I don't know anything and this post is stupid. Like I said, just an (un-educated) opinion for the sake of it.

  20. Zombo
    Date: Thu, Nov 3 2011 17:18:31

    the reason it runs on JVM is because of interoperability, simple as that. the fact that it runs on JVM has nothing to do with the pureness of the language. the syntax, grammar and features of the language would be the same regardless of where it runs. in fact there are compilers which will compile Java directly to machine code instead of just java bytecode. this is all transparent to the user. if you dont like that might as well use C++, java needs something to distinguish itself also java is not necessarily slower, you can create sophisticated JIT compilers. JIT means the java bytecode is only compiled to machine code right before it is needed (just in time), so you can dynamically adapt to the situation. In contrast, C is compiled statically to machine code before it is run, so it is not adaptive.

  21. Timbo
    Date: Fri, Nov 4 2011 16:32:24

    Java compilers sound like an interesting idea (to me at least, wouldn't expect many people to use them). Basically yeah, I do use C++ instead I just like the syntax of Java better I guess. I also figured that Java was in a JVM originally because there was no point it competing with C++. I'd heard of JIT compilers but never really knew what they were til now. Not sure what sort of things would cause the code to be generated differently in different situations though?

  22. Zombo
    Date: Fri, Nov 4 2011 16:46:57

    one example is you can profile the execution of the code. if you see some sections of the code are ran more often, you can prioritize the cache for them. there are many ways to translate the same piece of code into low-level instructions. but each method has different tradeoffs in terms of memory/cpu/cache/IO usage, so you adapatively choose the best

  23. Mike
    Date: Sat, Nov 12 2011 20:31:20

    Alright, so I've had some time to change things. Everything seems to be right, but I'm not getting any text displayed in the applet window when I run it. Any ideas? EDIT: Ha ha, I figured it out. I had this: [CODE]public void Paint (Graphics g)[/CODE] instead of this: [CODE]public void paint (graphics g)[/CODE] Now the only problem I have, is that all of the sentences are written in Uppercase letters, and some of the letters from the first words of the sentence are missing. This is what my output looks like:

  24. Zombo
    Date: Sun, Nov 13 2011 05:29:10

    hard to understand why its truncated without seeing the code... and for the caps thing, the easiest way to solve that is to caputre the whole sentence in a String variable, then pass the string to a new auxiliary function you create which will convert it to the right caps (first letter capitalized, everything else lower cap)

  25. Timbo
    Date: Sun, Nov 13 2011 06:26:22

    [quote=Timbo] Not quite sure why in your final line you are returning the entire string, bar the first character, in uppercase. (Remember indexes start at 0) [/quote] [quote=Mike] Now the only problem I have, is that all of the sentences are written in Uppercase letters, and some of the letters from the first words of the sentence are missing. [/quote] Substring returns a sub string, not a character. string.substring(1) will return the substring of string starting at index 1 (the second character in the string). The uppercase method that you are using will convert the entire string to uppercase, not just the character.

  26. Mike
    Date: Sun, Nov 13 2011 07:44:25

    Zombo;150179]hard to understand why its truncated without seeing the code... and for the caps thing, the easiest way to solve that is to caputre the whole sentence in a String variable, then pass the string to a new auxiliary function you create which will convert it to the right caps (first letter capitalized, everything else lower cap)[/QUOTE] Well it's because of what Timbo said. My instructor gave me the wrong information on the substring method. [QUOTE=Timbo wrote: Substring returns a sub string, not a character. string.substring(1) will return the substring of string starting at index 1 (the second character in the string). The uppercase method that you are using will convert the entire string to uppercase, not just the character.
    Yes thanks, I figured that's what it was. Now I just need to figure out how to get the first character uppercased. If substring returns the a string, and toUpperCase sets the WHOLE string to Uppercase, what method do I use then? EDIT: Ah, I just noticed I answered my own question. I got the app to work properly, thank you guys for the help. I'm going to have more questions later, so I'll be back ha ha

  27. Van
    Date: Fri, Nov 18 2011 22:58:32

    kay, I'm taking java right now in school...(just beginning) we have to write a code to increase a picture's blue by 55% (in RGB value) using a for loop I know how to do it using while loop and for-each loops now using for loops, I have no idea @.@ any help?

  28. Mike
    Date: Sat, Nov 19 2011 01:00:42

    @Van A for loop. [CODE]for (int i=0; i<20; i++) { Body of loop } [/CODE] EDIT: What exactly do you need help with?

  29. Zombo
    Date: Sat, Nov 19 2011 03:50:50

    a for-each loop is an advanced form of a loop, this page gives you the equivalent for loop\ http://leepoint.net/notes-java/flow/loops/foreach.html what it really is is syntactic sugar, just a convenient and shorthand form. I use for-each loops all the time.

  30. Mike
    Date: Sat, Nov 19 2011 08:00:13

    Zombo wrote: a for-each loop is an advanced form of a loop, this page gives you the equivalent for loop\ http://leepoint.net/notes-java/flow/loops/foreach.html what it really is is syntactic sugar, just a convenient and shorthand form. I use for-each loops all the time.
    Hmm, it is shorter. Nice.

  31. Mike
    Date: Mon, Nov 28 2011 02:55:34

    A couple of questions. I am writing a simple painter program that captures mouseDrag events and will draw whatever you want. I also have to make a "Tool Bar Window" which will contain radio buttons so that I could paint in a color that I choose, and a button that, when pressed, will clear whatever I have in the main applet window. Would my Tool Bar Window have to be an entirely different class? If so, would it be possible for this class to return a color? How would I get these two classes to "communicate" with each other?

  32. webspider
    Date: Mon, Nov 28 2011 18:38:53

    Communicate? Make some getter/setter-methods (for setting and getting the content of an attribute, obviously), that's the way to go.

  33. Zombo
    Date: Mon, Nov 28 2011 20:25:06

    one of the two classes will hold a reference to an object of the other class and call a method to grab the color.

  34. Mike
    Date: Tue, Nov 29 2011 00:09:51

    one of the two classes will hold a reference to an object of the other class and call a method to grab the color.
    So you CAN do it with two classes? Can I construct the frame in just one class too? Because that's what I tried to do first, but I can't seem to be able to set height and width. Sent from my SGH-T959 using Tapatalk

  35. Zombo
    Date: Tue, Nov 29 2011 00:57:52

    you can do it with as many classes as you want, theres really no limit. its all about convenience and good design its like writing: i can make a wall of text or separate into paragraphs. no difference in content and functionality

  36. Mike
    Date: Tue, Nov 29 2011 01:38:12

    Zombo wrote: you can do it with as many classes as you want, theres really no limit. its all about convenience and good design its like writing: i can make a wall of text or separate into paragraphs. no difference in content and functionality
    Ah alright, I see what you mean. Thank you sir :D Sent from my SGH-T959 using Tapatalk

  37. Mike
    Date: Tue, Nov 29 2011 09:05:55

    Alright, so this is what I have so far. This is my painter program class:

    Spoiler
    
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.Graphics;
    
    
    public class Buttons extends Applet
    {
    	private int xValue = -10,
    				yValue = -10;
    	
    	public void paint(Graphics g)
    	{
    		g.drawString("Drag the mouse to draw.", 10, 20);
    		g.fillOval(xValue, yValue, 4, 4);
    	}
    	
    	public void update(Graphics g)
    	{
    		paint(g);
    	}
    	
    	public boolean mouseDrag(Event evtObj, int x, int y)
    	{
    		xValue = x;
    		yValue = y;
    		repaint();
    		return true;
    	}
    }
    
    I know that if I want to implement my ToolBarWindow, I must call that class, with the method that returns a color value. That would have to look something like this right?
    Spoiler
     
    ToolBar myToolBar = new ToolBar();
    myToolbar.selectedColor(); //selectedColor is arbitrary
    
    Now, I seem to be having trouble with my ToolBar class that has the colors which you can select from. I currently have the return method to return a BOOLEAN value, but I know it can't be that, right? Would I have to implement actionListener to the following code instead, so that I can get the color value that I want?
    Spoiler
    
    import java.applet.Applet;
    import java.awt.*;
    
    public class ToolBarWindow extends Applet 
    {
    	Checkbox Red, Black, Magenta, Blue, Green, Yellow;
    	CheckboxGroup cbg;
    	Color selected = Color.black;
    	
    	public void init()
    	{
    		cbg = new CheckboxGroup();
    		
    		Red = new Checkbox("Red", cbg, true);
    		add(Red);
    		
    		Black = new Checkbox("Black", cbg, false);
    		add(Black);
    		
    		Magenta = new Checkbox("Magenta", cbg, false);
    		add(Magenta);
    		
    		Blue = new Checkbox("Blue", cbg, false);
    		add(Blue);
    		
    		Green = new Checkbox("Green", cbg, false);
    		add(Green);
    		
    		Yellow = new Checkbox("Yellow", cbg, false);
    		add(Yellow);
    		
    		Button clear = new Button("Clear");
    		add(clear);
    	}
    	public boolean action (Event evtObj, Object arg)
    	{
    		if(evtObj.target instanceof Checkbox)
    			if(arg.equals(Red))
    				selected = Color.red;
    			else if (arg.equals(Black))
    				selected = Color.black;
    			else if (arg.equals(Magenta))
    				selected = Color.magenta;
    			else if (arg.equals(Blue))
    				selected = Color.blue;
    			else if (arg.equals(Green))
    				selected = Color.green;
    			else if (arg.equals(Yellow))
    				selected = Color.green;
    		}
    }
    

  38. hahakumquat
    Date: Tue, Dec 13 2011 02:30:37

    Hello smart people. I have a question. I have to implement a program that takes a string of letters and returns the string with each letter 10 places away. So if the string is "ABC", it would return "KLM", "HELLO" would become "ROVVY". So, here's what I did.

    Spoilerpublic String wordEncoder(String word) { char letter=word.charAt(0); String newWord=""; for (int k=0; k This passes every test given to it...except for a section called "other tests". I can't figure out what situation would result in an incorrect return for this. Can any of you spot a problem that might occur? All characters are alphabet letters in caps. PS, I'm a beginner. Go easy on my redundant programming logic :D. Of course, if you have any better methods that you MUST share, feel free to tell me!

  39. Zombo
    Date: Tue, Dec 13 2011 03:19:04

    well other tests can be anything its possible they want you to do input validation -> verify that the word is valid before processing it. for example if you're given "012" these are not letters

  40. Mats
    Date: Wed, Dec 14 2011 17:30:48

    Zombo wrote: its possible they want you to do input validation -> verify that the word is valid before processing it. for example if you're given "012" these are not letters
    Yes and maybe check it's spelt correctly.