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

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.

Related

Java array values gets overwritten

I am new to Java and this is a very basic question.
However I struggle to find a solution, so hopefully someone could give me some pointers.
I am trying to fill values into an array "addedPlayer".
However, every time I run the AddPlayer() method it is initialiezed to zero again.
How can I structure this in a better way?
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void AddPlayer() {
int[] addedPlayer;
addedPlayer = new int[500];
System.out.println(" *** Add new player *** ");
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
System.out.println(addedPlayer[0]);
for (int j = 0; j < addedPlayer.length; j++) {
if (addedPlayer[j] != 0) {
} else {
addedPlayer[j] = p.GetAge();
System.out.println(addedPlayer[j]);
System.out.println(j);
break;
}
}
}
public void EditPlayer() {
//empty
}
public void ListPlayer() {
//empty
}
#Override
public void run(String... args) throws Exception {
while (true) {
System.out.println(" *** MENY *** ");
System.out.println(" 1. Add player ");
System.out.println(" 2. Edit player ");//ÖKurs
System.out.println(" 3. List player ");
System.out.println(" 100. Exit ");
System.out.println("Ange val");
int sel = Integer.parseInt(System.console().readLine());
if (sel == 100) break;
if (sel == 1) AddPlayer();
if (sel == 2) EditPlayer();
if (sel == 3) AddPlayer();
}
}
}
Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see #g.momo's answer.
int[] addedPlayer; addedPlayer = new int[500];
It gets overridden because you are creating an new local var addedPlayer, and then setting all values to 0 (addedPlayer = new int[500];) I'm assuming you would want addedPlayer to be global, so don't define it locally and set it to 0.
Also, should addedPlayer be a player[] or just a player rather than an int[]? Plus, you didn't close the function in the code you gave us, so is there more missing or did you just not close it?
Your code and your expectations are completely differents.
Read this and tell us if you understand. It is the way I would have written if I were you . But it is NOT TESTED:
public class AddPlayer { // you create a class
player[] addedPlayer; // array of players
int index;
public AddPlayer() { // constructor of the class
addedPlayer = new player[500]; // max 500 players
index = 0;
}
public void addPlayer(player p) {
if(index < 500) {
addedPlayer[index] = p; // add at index,
index = index + 1; // then increment index for the next added player
}
}
public static void main(String... args) {
AddPlayer addPlayers = new AddPlayer();
int i = 0;
while(i < 5) { // will run 5 times, so only 5 players will be added. Change to stop when you will need
// here your read console inputs
System.out.println(" *** Add new player *** "+ (i+1));
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
// initialize the player
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
addPlayers.addPlayer(p); // add in the array
i++;
}
}
}

Assign new value to an Array using Enhanced For Loop

I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}

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);
}
}

Strange issue with an array

So I'm in the middle of working on a class called planner [no main in it as it's a separate class], but I'm having an issue with declaring an array with eclipse. You will need to enter it in eclipse to see what it is because I have no idea what it means by 'Syntax error on token ";", , expected'.
Here is the code:
import java.util.Scanner;
public class Planner {
private int maxEvents = 1000;
private int numEvents = 0;
private int choice;
int[] anArray;
anArray = new int [1000];
public void Planner() {
Scanner scan = new Scanner (System.in);
System.out.print("Press 1 to add an event. 2 to display events for the day. 3 to display events for the week. 4 to quit: ");
choice = scan.nextInt();
if (choice == 1){addEvent();}
if (choice == 2){displayOneDate();}
if (choice == 3){displayOneWeek();}
if (choice == 4){System.out.println("Have a good day.");}
else {Planner();}
}
public void addEvent() {
Event newEvent = new Event();
if (numEvents == maxEvents){System.out.println("Error: No more room.");}
else {
for (int i=0; anArray.length > i; i++) {
numEvents++;
newEvent.getEventFromUser();
}
}
}
public void displayOneDate() {
System.out.println("Event one: " + anArray[0]);
}
public void displayOneWeek() {
}
}
When you declare
int[] anArray;
anArray = new int [1000];
it should be
int[] anArray = new int [1000];
You cannot have executable code in class directly. You should have it either in method or constructor.
Otherwise if you want initialize the array you have to write like this int[] anArray = new int [1000];

What am I doing wrong with using arrays?

I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH

Categories