Reputation: 1615
I want to make a program in Java in Eclipse, what tell me, if I can make the triangle or not. It is my code:
import java.io.IOException;
public class haromszog {
public static void main(String[] args) throws IOException {
int a;
int b;
int c;
System.out.print("Please insert the 'a' side of the triangle:");
a = System.in.read();
System.out.print("Please insert the 'b' side of the triangle:");
b = System.in.read();
System.out.print("Please insert the 'c' side of the triangle:");
c = System.in.read();
if ((a+b)>c)
{
if ((a+c)>b)
{
if ((b+c)>a)
{System.out.print("You can make this triangle");
}
else
System.out.print("You can't make this triangle");
}
}
}
}
The Eclipse, can run it, but it writes:
Please insert the 'a' side of the triangle: (for example I write: ) 5
Please insert the 'b' side of the triangle:
Please insert the 'c' side of the triangle:
You can't make this triangle
And I can't write anything to the b and c side. What's the problem with this?
Upvotes: 0
Views: 347
Reputation: 38531
Adding to Joachim's answer, try this:
import java.io.IOException;
import java.util.Scanner;
public class foo {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
System.out.print("Please insert the 'a' side of the triangle:");
int a = s.nextInt();
System.out.print("Please insert the 'b' side of the triangle:");
int b = s.nextInt();
System.out.print("Please insert the 'c' side of the triangle:");
int c = s.nextInt();
}
}
Upvotes: 1
Reputation: 36229
You read a byte, so if it is the ascii-charcter '5' it is not the number 5, but 53. Your next problem is Carriage-Return which is read as the next byte.
Use the java.util.Scanner class instead:
Scanner sc = new Scanner (System.in);
int a = sc.nextInt ();
Upvotes: 1
Reputation: 51935
In addition to the System.in.read() problem, you need to combine your if statements, because that the else clause currently only applies to the inner one.
if ((a+b)>c && (a+c)>b && (b+c)>a) {
System.out.print("You can make this triangle");
}
else {
System.out.print("You can't make this triangle");
}
Upvotes: 2
Reputation: 60065
From http://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.html:
read() : Reads the next byte of data from the input stream.
You read not integer, but char code.
You should probably do:
java.util.Scanner s = new java.util.Scanner(System.in);
int k = s.nextInt();
Upvotes: 5
Reputation: 308021
System.in.read()
reads a single byte
from standard input of your application. That's almost certainly not what you want (unless something is passing binary data to your application).
You could try System.console().readLine()
instead (followed by Integer.parseInt()
to convert the resulting String
to an int
).
Upvotes: 8