Is it possible to use a single input in different objects? - java

The both codes below are from different class files.
I'm trying to use the input from spinWheels for pull.
Is that possible?
public int spinWheels(int betAmt)
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(System.in);
betAmt = kb.nextInt();
}
public void pull(int bet)
{
betAmt = bet;
totalcoins = totalcoins - bet;
}

You mean like this?
int x = 0;
spinWheels(x);
pull(x);

It is possible but there are several things that you must do first. Say you have a class A:
class A{
public int spinWheels(int betAmt)
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(System.in);
return kb.nextInt(); //I assume you need this value later
//you must return an int here
}
}
and you have a second class B:
class B{
public void pull()
{
//you need a reference to an Object of type A
A a = new A();
bet = a.spinWheels();
totalcoins = totalcoins - bet;
}
}
Of course the above code is very simplistic, without knowing what you want to achieve it is not possible to say more.

You could just use
public int spinWheels()
{
String[] aWheel = new String[5];
Scanner kb = new Scanner(kb.nextInt());
...
}
I don't understand why you'd want to pass betAmt as an argument if you're going to run it over anyway...

Related

Adding more variables to an array of objects in java

I've made a bit of a mess on a project of mine. I have to create an array of objects. I have made an array but it only has 1 field 'myMonths' referring to the length of time of the project.
In my main method:
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
//myMonths = new int[amount];
System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
System.out.println("What was the duration of your projects in months?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//display error message
if((a < 2) || (a > 12)){
System.out.println(" Please enter an amount between 2 and 12 months. ");
}
//add to the array
else{
myMonths[index++] = a;
}
}
calc.setMyMonths(myMonths); //creating the object
break;
In my class on separate file:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
I should have added in two more fields, both strings. Is there a way I can add more fields/attributes to this array and have them viewable at the same time under 1 index? For example at [0] projectName, projectManager, myMonths ie(string, string, integer).
Any advice would be great, I am getting really confused with OOP. Thanks in advance!
Yes, create a class containing your three properties:
class MyContainer {
public MyContainer(int durationMonths, String projectName, String projectManager) {
this.durationMonths = durationMonths;
this.projectName = projectName;
this.projetManager = projectManager;
}
public int durationMonths;
public String projectName;
public String projectManager;
}
Then create an array of this class with:
MyContainer[] myArray = new MyContainer[numberOfProjects];
Add items to the array like this:
myArray[0] = new MyContainer(3, "super project", "awesome manager");

Using an input from the user to assign to a variable in a second class

I am making a program with two classes, one to create methods and the other as the tester class. I am having difficulties assigning the input to a new variable, which needs to be used to invoke the methods from the other class.
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int obj = new NumberUtility(0);
System.out.println("Enter a number. Enter 0 to end");
obj = scan.nextInt();
As example here is the beginning of the other class
public class NumberUtility {
int n = 0;
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
public int getN() {
return n;
}
public boolean isEven() {
if((n % 2 == 0)) {
return true;
} else
return false;
}
My code is incomplete elsewhere but that is the main issue I have been trying to work around. Since if I set it to an int, it won't work. Sorry if this is a stupid question, I am new to java coding.
With this line:
int obj = new NumberUtility(0);
you are attempting to assign a new NumberUtility object to the variable obj which is of type int. You cannot do that! That's like trying to create a doghouse, and then shoving your dog into a birdhouse. They're just not compatible.
As well, later, you try to reassign obj to the result of scan, which would work, but probably not what you want, as obj is still an int:
obj = scan.nextInt();
I think what you want to do is something like the following:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a number. Enter 0 to end");
// Read a number from the scanner
int number = scan.nextInt();
// Create a new NumberUtility from this primitive integer
NumberUtility obj = new NumberUtility(number);
System.out.println("Even? " + obj.isEven());
By the way, you can simplify your isEven method as well:
public boolean isEven() {
return (n % 2 == 0);
}
Edit: I see I'm not done yet.
In the NumberUtility class, you have defined a constructor for the class:
public NumberUtility(int n) {
getN();
isEven();
isOdd();
}
This seems like an odd thing to do. You are ignoring the input (int n) and then calling all the methods of the class which don't really do much.
I think you want your constructor to be something like this:
public NumberUtility(int input_n) {
// Save the constructor's input parameter to the member field 'n'
this.n = input_n;
}

How to use one scanner for both integers and text?

I need to make a program that allows me to ask the user for a few numbers and keep doing that until the user enters a 'q' but i cant seem the get the hasNextInt to work as i thought it worked. I am very new to Java and doing the ground course atm.
Here is what i have done so far
public class Matte
{
public static void main (String[] args)
{
int r1 = 0;
int h1 = 0;
int r2 = 0;
int h2 = 0;
int level = 1;
String choice = new String();
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
if(!values.hasNextInt())
r1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
r2 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h2 = values.nextInt();
else choice = values.nextLine();
}
}
}
I want to save what ever text is typed in the scanner in the "choice" variable
How do i do it??
I didn't really understand your problem, but here is a solution for your problem, adding these integers to an ArrayList and stoping the program when the user types 'q'. Hope it helps you. Cheers!
public class Matte
{
public static void main (String[] args)
{
ArrayList<Integer> numbers = new ArrayList();
int level = 1;
String choice;
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
while(true){
choice = values.nextLine();
if(choice.equals("q"))
break;
else
numbers.add(Integer.parseInt(choice));
}
}
}
}

How can I pass an Array from one class to another?

I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
}
}
import java.util.Scanner;
public class takeAGuess {
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
public class board {
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
}
I already tried these lines:
new[] board = board.Createboard();
int board[] = board.Createboard();
{
int board = new board();
board = createBoard();
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes therefore I create lots of them.
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
where is playboard defined?
And... so much classes! Use methods in the Main class instead, it'll make your job lighter.

create objects using user input number of object [duplicate]

This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 6 years ago.
I am a new user in java. As a programming exercise i have to make a program that - asks how many objects the user wants to create and then creates them. Class also calls for a class method that prints the number of created objects. also
to write the class which creates the objects. Class must be able to keep track of the number of created objects. Class also needs the method that prints the number of objects. Check the completed class for the names of the class and method.
I have tried following but have not reached any where so i am expecting some help: Please help!!
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
int count;
public void numberOfObjects(){
System.out.println(count);
}
}
}
You forgot 3 things:
1- to increment the count of the objects when they are created. You can do so in the Thing constructor.
2- declare the count variable as static to allow the variable to be shared between all objects of type Thing.
3 - to declare the numberOfObjects method as static since it is a class method that you are accessing via the Thing class
Try this:
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
private static int count = 0;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
}
class Box
{
//Keep track of all your objects
Thing[] objs;
int cursor;
public Box(int countOfObjects)
{
objs = new Thing[countOfObjects];
}
//add new object to the array
public void add(Thing thing)
{
objs[cursor++] = thing
}
//gets the object
public Thing getThing(int pos)
{
if(pos < 0 || pos >= objs.lenght())
throw;
return objs[pos];
}
//count the objects
public int numberOfObjects()
{
System.out.println(objs.lenght());
return objs.lenght();
}
}
}
class Thing()
{
//any field you need to store
}
Your main should look like this
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Box box = new Box(amount);
for(int i = 0; i<amount; i++) {
box.Add(new Thing());
}
box.numberOfObjects();
}
Declare count as static and add count in constructor.Another import thing,move Thing class out of NumberOfObjects Class,otherwise, the Thing class is an inner class, you will need create NumberOfObjects instance first and use this object to create Thing instance.
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
}
class Thing{
private static int count ;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}

Categories