Java Beginners

Moderators: zibadian
Number of threads: 1285
Number of posts: 2739

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
New To Java - Input Number Won't Prompt, Wrong Result Posted by jhuwalker on 31 Jan 2011 at 9:54 AM
A simple program that compiled success, but can not input second number, no prompt. number doesn't match the first number input at keyboard with display on output. Thanks

========================
/* Enter two number at prompt
* Add both number
* Print out Total
*
* 1/31/2011
* Code Name Add2Number.java
*/

import java.io.*;

class Add2Number {
public static void main(String[] args)
throws java.io.IOException {
int n1, n2, Total;

System.out.println("Enter Your First Number:");
n1 = (int) System.in.read();
System.out.println("Enter Your Second Number:");
n2 = (int) System.in.read();

Total = n1 + n2;
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);

System.out.println("Total = " + Total);
}
}

Report
Re: New To Java - Input Number Won't Prompt, Wrong Result Posted by krishbaloda on 1 Feb 2011 at 5:20 AM
import java.io.*;

class Add2Number {
public static void main(String[] args)
throws java.io.IOException {
int n1=0, n2=0, Total;
//create object of scanner
Scanner kbd = new Scanner(System.in);

System.out.println("Enter Your First Number:");

//change here

n1 = kbd.nextInt();

System.out.println("Enter Your Second Number:");

//change here

n2 = kbd.nextInt();


Total = n1 + n2;
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);

System.out.println("Total = " + Total);
}
}

this will work fine

Report
Re: New To Java - Input Number Won't Prompt, Wrong Result Posted by jhuwalker on 1 Feb 2011 at 2:35 PM
Thanks krishbaloda ! the scanner is working



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.