Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

Beginner, this will be a quick fix, so please check it out!!

Thread view: 
the_transcriber@yahoo.com - 05 Oct 2007 09:43 GMT
Hi, extreme noob here (less than one week of Java exerience, or any
programming exp)

This program i am writing from a book is suppose to ask the question
"How many gumballs? How mand kids? " , and then allow the user to
input the 2 answers. for example :    80  4

but it doesn't ask that question, it just answers without asking!  any
help... ? this is from the Beginner Programming with Java for Dummies
- 2nd Edition. I typed it straight out of the book, and checked it
vary carefully. the output im currently gettins is... "Each kid gets 6
gumballs"

import java.util.Scanner;

class KeepingMoreKidsQuiet {

    public static void main(String args[]) {
        Scanner myScanner = new Scanner(System.in);
        int gumballs;
        int kids;
        int gumballsPerKid;

        System.out.print("How many gumballs? How many kids? ");

        gumballs = myScanner.nextInt();
        kids = myScanner.nextInt();

        gumballsPerKid = gumballs / kids;

        System.out.print("Each kid gets ");
        System.out.print(gumballsPerKid);
        System.out.println(" gumballs.");
    }
}
Gordon Beaton - 05 Oct 2007 09:47 GMT
> This program i am writing from a book is suppose to ask the question
> "How many gumballs? How mand kids? " , and then allow the user to
> input the 2 answers. for example :    80  4
>
> but it doesn't ask that question, it just answers without asking!

Try using System.out.println() to ask the questions, instead of
System.out.print().

/gordon

--
Chris ( Val ) - 05 Oct 2007 12:46 GMT
On Oct 5, 6:43 pm, the_transcri...@yahoo.com wrote:
> Hi, extreme noob here (less than one week of Java exerience, or any
> programming exp)
[quoted text clipped - 20 lines]
>
>                 System.out.print("How many gumballs? How many kids? ");

[snip]

You could use the 'println()' method instead.

Alternatively, you can add a new line to your string in the 'print()'
method, i.e: System.out.print("How many gumballs? How many kids?\n");

However, and more precicely, I would rather flush the stream
explicitly,
right after the 'print()' method call. This has the advantage of
pacing
your cursore for entry on the same line, which you would probably
like :-)

System.out.flush();

HTH,
Chris
the_transcriber@yahoo.com - 05 Oct 2007 16:18 GMT
> On Oct 5, 6:43 pm, the_transcri...@yahoo.com wrote:
>
[quoted text clipped - 41 lines]
> HTH,
> Chris

Thanks, just a couple questions. What does "flush" refer to, or mean?
and also, what does the \n  mean in the quote?  Thanks for your help!
Lew - 05 Oct 2007 16:21 GMT
> What does "flush" refer to, or mean?

<http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html>
specifically
<http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html#flush()>

> and also, what does the \n  mean in the quote?  Thanks for your help!

<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html>

Read the entire tutorial.

Signature

Lew

the_transcriber@yahoo.com - 05 Oct 2007 16:49 GMT
THanks for your help!
Daniel Pitts - 05 Oct 2007 16:43 GMT
>> On Oct 5, 6:43 pm, the_transcri...@yahoo.com wrote:
>>
[quoted text clipped - 37 lines]
> Thanks, just a couple questions. What does "flush" refer to, or mean?
> and also, what does the \n  mean in the quote?  Thanks for your help!

You'll find a lot of things will "buffer" data.  A buffer is usually a
place where its fast to add/remove data to before it gets "sent"
somewhere else.  For instance, System.out.print will buffer somewhere,
because its faster than writing a whole lot of small messages to the
screen in a lot of cases.  Flush tells the "buffer" to send everything
its accumulated.

Some things flush automatically, and some things don't have a buffer.
System.out.println will flush automatically, including anything that was
buffered BEFORE the call.
System.out.print may buffer, and might not flush.

Now, the next important piece of information:  Just because something is
buffered, don't expect that none of your output will happen.  Buffers
tend to be of limited size, and will flush themselves before/as they
fill up.  If this happens, you might send part of your message before
the rest of it. Especially if you don't flush.

HTH,
Daniel.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

venu - 05 Oct 2007 16:05 GMT
On Oct 5, 1:43 pm, the_transcri...@yahoo.com wrote:
> Hi, extreme noob here (less than one week of Java exerience, or any
> programming exp)
[quoted text clipped - 34 lines]
>
> - Show quoted text -

try using System.out.println(" xxxxx ");
the ' println()' takes the control to the next line, whereas print()
keeps it on the same line. Please initialize all variables to 0 in a
Java program. Well the last part is just my superstition.
the_transcriber@yahoo.com - 05 Oct 2007 16:17 GMT
> On Oct 5, 1:43 pm, the_transcri...@yahoo.com wrote:
>
[quoted text clipped - 41 lines]
> keeps it on the same line. Please initialize all variables to 0 in a
> Java program. Well the last part is just my superstition.

Cool thanks I'll try it. Also, im so extremely noob, that i don't know
exactly what you mean by init all variables to 0? Can you give me an
example from my code? thanks
Lew - 05 Oct 2007 16:17 GMT
> Please initialize all variables to 0 in a Java program.
> Well the last part is just my superstition.

Yes, it is, and not a good one.

The better rule is to initialize variables to their initial value.  If that
happens to be 0 (or equivalent), good (albeit completely unnecessary to state
explicitly for instance or class variables).  If it isn't 0 (or equivalent),
then why initialize to a different value from its initial value?

In the case of the OP:
>>                 int gumballs;
>>                 int kids;
[quoted text clipped - 6 lines]
>>
>>                 gumballsPerKid = gumballs / kids;

better would have been to initialize to the initial value (which is only 0 if
gumballs's initial value is 0 and kids's isn't):

 System.out.print("How many gumballs? How many kids? ");

 int gumballs = myScanner.nextInt();
 int kids = myScanner.nextInt();
 int gumballsPerKid = (kids == 0? 0 : gumballs / kids);

Signature

Lew

Daniel Pitts - 05 Oct 2007 16:49 GMT
[snip]
> Please initialize all variables to 0 in a
> Java program. Well the last part is just my superstition.

Please do NOT initialize all variables to 0 in a Java program!

You should not declare your variables until they are first needed and
can be assigned.  If possible, its good practice to declare them final.
This ensures that they will only ever be initialized once, even if you
go through different branches to initialize them.

final int pageSize;
if (pageNumber == 0) {
   pageSize = 10;
} else {
   pageSize = 20;
}
someOtherObject.doSomethingWithPageSize(pageSize);
Better yet, if you can initialize a variable to two different values,
but only use one, make it into a method:

private int getPageSize() {
    if (pageNumber == 0) {
       return 10;
    } else {
       return 20;
    }
}

// then you can use:
final int pageSize = getPageSize();
someOtherObject.doSomethingWithPageSize(pageSize);

Or even better, "inline" that variable (don't use the variable, just use
what you assigned to it, since it has a meaningful name now)

someOtherObject.doSomethingWithPageSize(getPageSize());

Even if you call getPageSize a few times, its better design.  If and
only if you find that calling that method slows down your application
beyond a reasonable level should you "optimize" to saving the value.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Lew - 05 Oct 2007 21:41 GMT
> Please do NOT initialize all variables to 0 in a Java program!
>
> You should not declare your variables until they are first needed and
> can be assigned.  If possible, its good practice to declare them final.
> This ensures that they will only ever be initialized once, even if you
> go through different branches to initialize them.
...
> Or even better, "inline" that variable (don't use the variable, just use
> what you assigned to it, since it has a meaningful name now)
>
> someOtherObject.doSomethingWithPageSize(getPageSize());

Daniel's excellent advice translated to the example:

boolean terminated;
do
{
  System.out.print("How many gumballs? How many kids? ");
  System.out.flush();

  final int gumballs = myScanner.nextInt();
  final int kids = myScanner.nextInt();
  final int gumballsPerKid = (kids == 0? 0 : gumballs / kids);

  System.out.println( "" + gumballs +" gumballs for "+
                      kids +" kids = "+
                      gumballsPerKid +" gumballs per kid." );
  System.out.print( "Continue? " );
  System.out.flush();

  final String cont = myScanner.next();
  terminated = (cont.length() == 0
                || Character.toLowerCase( cont.charAt(0) ) != 'y' );
} while ( ! terminated );

Naturally there are several ways to recast this code snippet.  This one is
just to tie together advice from this thread about flush() and declaration and
initialization.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.