Reputation: 25
Beginner to Java here. I've been researching how to do this, but I guess I'm researching the wrong thing.. My program inputs numbers and calculates what the user inputted. I figured out how to connect a different class (the one that calculates everything) to the main class (the one that will just output everything). What I'm finding difficulty on is how to connect a boolean, not a void, method to the main class.
public class Driver
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); //forgot to add scanner
ExampleClass ex = new ExampleClass();
System.out.println("Enter numbers <enter -1 to stop>");
number = in.nextInt(); //user inputs a number
boolean inputData = true; //researched about this, but it doesn't work
ex.inputData(); //doesn't work either
}
}
second class:
public class ExampleClass
{
int numberOfThings = 0;
int number = 0;
int sum = 0;
public ExampleClass()
{
// constructor
}
public boolean inputData(int number)
{
if(number >= 0)
{
numberOfThings++;
}
else if (number <= 0)
{
System.out.println("Out of range");
return false;
}
return true;
}
}
I'm pretty sure my if statement needs work, my only question is how do I connect the boolean method to my main class (Driver)? I'm trying to piece together how to connect methods and such before I start my real project.
boolean inputData = true;
ex.inputData();
does not work.
I just provided an example, my coding isn't complete yet.
update: this worked, posting this in case anyone searching needs this.
boolean inputData = true;
while (inputData)
{
Scanner in = new Scanner(System.in);
number = in.nextInt();
inputData = ex.inputData(in.nextInt());
}
Upvotes: 1
Views: 1878
Reputation: 13483
Possibly loop until the input is false? I don't really know what you want:
System.out.println("Enter numbers <enter -1 to stop>");
ExampleClass ex = new ExampleClass();
boolean inputData = true;
while (inputData) { // loop until it's false to keep gaining numbers
Scanner input = new Scanner(System.in); // to get input
inputData = ex.inputData(input.nextInt()); // equals the return of inputData
}
Upvotes: 1
Reputation: 41188
You nearly have it, instead of:
boolean inputData = true;
ex.inputData();
do
Scanner in = new Scanner(System.in);
boolean inputData = ex.inputData(in.nextInt());
Upvotes: 2