Need help: input int from console and pass it into method in different class and do math
i'm a beginner, Need help, Please!!!
I want to read optional number "a" from console and then store it in variable to use as passing to a different class (different .java file). and pint the sum separetely by optional inputting.
How do i code the 2 classes? thanks
/*
* DemoApp.java
*/
public c开发者_StackOverflowlass DemoApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a;
System.out.println("Input one of the following 3 numbers: 100, 200, 300");
System.out.print("Enter: ");
a = input.nextInt();
TestApplication testapp = new TestApplication();
testapp.test(a);
}
}
/*
* TestApplication.java
*
*/
public class TestApplication {
private int a;
public void test(int a) {
this.a = a; // TODO: where to get the "a"? (entered by users from console)
System.out.println("The number_a was passed in: "+a);
}
protected void printNum() throws Exception {
int num;
switch (a) {
case 100:
num = num + 10;
break;
case 200:
num = num + 20;
break;
case 300:
num = num + 30;
break;
default:
// TODO: unexpected number input. throw();
break;
}
System.out.println("I got a sum number"+num);
}
}
i just wanted to keep my question simple for the demo code. hehe :)
the secenio is that i want to input 3 number separetely from console, pass it to the second class B, in the the second class B, I need to build a fully-qualified message following the protocol (one of the 3 number will be needed), and then send the message to RS-232 port. all the encoding/decoding and send/ack job is done by the third class C. btw, the second class B is derived from the third class C.
in the demo code, it seems like the "a" is not passed into the printNum() method.
any help will be very appreciated!
Your code looks fine... Are you wondering how to compile Java programs with two source files like this? Try...
javac DemoApp.java TestApplication.java
java DemoApp
and it should work. Unless you're using an IDE such as NetBeans or Eclipse, in which case they should handle all of this for you.
Your code looks fine. The one thing I don't see is a call to your printNum
method. You could put a call to that in your test(int)
method, so it would look like this:
public void test(int a) {
this.a = a; // TODO: where to get the "a"? (entered by users from console)
System.out.println("The number_a was passed in: "+a);
printNum();
}
A couple points on printNum
:
- there is no place in the method that will
throw
a checkedException
, so you should removethrows Exception
from the signature. - you perform math on the
num
var as if it would be modified many times, but each case of theswitch
breaks and there is no loop in the method, so there should be no+=
required (this really shouldnt compile, asnum
will not have been initialized be the time it is dereferenced).
精彩评论