Archived

This topic is now archived and is closed to further replies.

Sir_Spritely

[java] MS Visual J++ 6 compiler problem

Recommended Posts

Just wondering if anyone knew why the program below does not work as it should. What is happening is the computer is prompting for the first number to be entered as it should but it is not requested a number be entered for the second prompt and then coming out with some totally bizzare answer. I have tried debugging but that does not shed any light on the situation. import java.io.*; public class Class1 { public static void main (String [] args) throws IOException { int num1, num2, sum; System.out.println ("Input a number: "); num1 = System.in.read(); System.out.println ("Input another number: "); num2 = System.in.read(); sum = num1 + num2; System.out.println ("The total is " + sum ); } } This is an example I have been given from the course I am doing. I have had to change the following lines from the example I was given, num1 = Course_io.readInt(); num2 = Course_io.readInt(); To the ones you see in the code above. Help appreciated as I am a Java newbie as is probably very obvious

Share this post


Link to post
Share on other sites
Firstly, I''d recommend switching development environments. Visual J++ is 4 yrs old, and supports only Java 1.1. We''re now at 1.4.1.

But I''m digressing. Back to your problem. You''ll need to ''wrap'' the System.in InputStream in a DataInputStream before using it. THis makes Java''s IO a pain to use for beginners, as it is very different from most mainstream programming languages. Here''s code below that should read an integer and print it out properly


  
import java.io.*;
public class Class1
{
public static void main (String [] args)
throws IOException {
int num1, num2, sum;
//create a new DataInputStream

DataInputStream in = new DataInputStream(System.in);

System.out.println ("Input a number: ");
num1 = in.readInt();
System.out.println ("Input another number: ");
num2 = in.readInt();
sum = num1 + num2;
System.out.println ("The total is " + sum );

}
}

Share this post


Link to post
Share on other sites