How to pass objects between two Java classes with main - java

Basically I create a custom object in one program and instantiate with values in one program, then I create another program and want to print the instantiated object output.
import java.util.Scanner;
class example {
int value;
String name;
String city;
}
public class Yummy21 {
static example[] obj=new example[3];
static Scanner input=new Scanner(System.in);
public static void main(String args[])
{
init();
}
public static void init()
{
for(int i=0;i<3;i++)
{
obj[i]=new example();
}
for(int i=0;i<3;i++)
{
System.out.println("for the object "+i+" enter the name ");
obj[i].name=input.next();
System.out.println("for the object "+i+" enter the city ");
obj[i].city=input.next();
System.out.println("for the object "+i+" enter the name ");
obj[i].value=input.nextInt();
}
}
}
And the next program:
public class Yummy22 extends Yummy21 {
public static void main(String args[])
{
for(int j=0;j<3;j++)
{
System.out.println("the value of the object["+j+"].name is "+obj[j].name);
}
}
}
The first program works fine, meaning it takes the values and the second program shows NullPointerException.

Yummy22.main does not invoke Yummy21.init. perhaps put a
static {
init();
}
in Yummy21.
This being said, these 3 classes are abominations of Java. Please at least follow naming conventions. Class example should be Example. Also better to code all this with object level fields, constructors and non static members

serialize the data from program 1 and write it to disk and then read it from program 2.

Related

Calling non-static method (in a different class) from static

I've done some looking around on here for a solution, but I can't find one. I tried these ones and many others, and I run into the same issue.
I am trying to make a simple text game, and I run into the issue where I have a main class, and a class called "gameboard" that I have as an array defined like this:
static GameBoard[] gameboard = new GameBoard[9];
Now, this works fine until I try to change the characteristics of a single one of these array objects. I will do:
gameboard[input].setState(2);
and the specific instance of gameboard that should change will not be the only one: all of them change when I do this. It's weird. Only gameboard[**input**] should change, not all 9 of the gameboard instances. EVERY variable and method I have is "static", but because of the main method (public static void main...), everything seems to have to be static. How do I get rid of all this static?
GameBoard Class
package com.name.tictactoe;
public class GameBoard {
char[] States = {'N','X','O'};
char state;
public void setState(int s){
state = States[s];
}
public char getState(){
return state;
}
}
Main class (called Game)
package com.name.tictactoe;
import java.util.Scanner;
public class Game {
static boolean turn, win;
static GameBoard[] gameboard;
static Scanner kb = new Scanner(System.in);
static int input;
public static void main(String[] args){
gameboard = new GameBoard[9];
reset();
displayStates();
askTurn();
displayStates();
askTurn();
}
public static void askTurn() {
System.out.println();
System.out.println();
System.out.println("Where do you want to go? Use the numbers shown, where the first segment is the top and the last is the bottom - left to right.");
input = kb.nextInt();
if(input > 8){
System.out.println("Input out of bounds. Game over by default.");
try {
Thread.sleep(1000000000);} catch (InterruptedException e) {e.printStackTrace();}
}
gameboard[input].setState(2);
}
public static void reset(){
for(int i = 0; i < 9; i++){
gameboard[i].setState(0);
}
}
public static void displayStates(){
for(int i = 0; i < 9; i++){
System.out.print(gameboard[i].getState() + " ");
if(i ==2 || i ==5){
System.out.print(" II ");
}
}
System.out.println();
for(int i = 0; i < 9; i++){
System.out.print(i + " ");
if(i ==2 || i ==5){
System.out.print(" II ");
}
}
System.out.println();
}
}
UPDATE: The current answers don't work. Although Eclipse doesn't realize this, making GameBoard non-static causes null pointer exceptions when any method in it is referenced.
A static variable belongs to the class, not the object, so of course all of your GameBoards are being affected!
Just because you're in a static method doesn't mean you can't manipulate instance variables. First, make everything in your GameBoard class non-static (unless you really do need some of the values shared across all instances). This includes your instance variables and your getter/setter methods.
If your program works exclusively from the main method, then keep your GameBoard[] object static. Then, when you make that method call:
gameboard[input].setState(2);
This will change only the state of the GameBoard at index input.
Edit:
To instantiate your GameBoard[] with basic GameBoard objects inside of it, you can do this at the beginning of your main method:
for(int x=0; x<gameboard.length; x++) {
gameboard[x] = new GameBoard(); //Assuming you want to use the default constructor
}
The other objects in your array should not change. Can you add some more code for more context?
As far as I can understand you, you are doing something like:
public class Main {
public static String[] strings = new String[2];
public static void main(String[] args) {
strings[0] = "test";
System.out.println(strings[1]);
}
}
In my example output is "null" as expected.
How do I get rid of all this static?
Just create instances of your objects in the main function.
GameBoard[] gameboard = new GameBoard[9];
For what you describe to happen all the elements of the gameboard array must be set to the same object (nothing to do with the array being static), check your code where you populate the gameBoard array with new instances of the GameBoard class for a bug that could cause the same instance to be written to all elements (or post that code here so people can see the problem).

Making a program into two different classes

So I had to write a code that takes a word and reverse it I got it to work but for my homework I had to make it into two classes a tester class and a main class how do I do that?
public static void main(String args[])
{
String original = "";
String reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + original.charAt(i);
}
System.out.println("Reverse of entered string is: "+reverse);
}
You create two classes. You can even put a main method in both of them.
public class Homework {
public static void main(String[] args) {
// Code here to prompt user for string and to print reversed string
}
static String reverse(String input) {
// Code here to do the actual reverse logic, returning reversed string
}
}
public class HomeworkTest {
public static void main(String[] args) {
test("Hello", "olleH");
test("This is a test", "tset a si sihT");
}
private static void test(String input, String expected) {
String rev = Homework.reverse(input);
System.out.println(input + ": " + rev);
if (! expected.equals(rev))
System.out.println(" ** NOT AS EXPECTED: " + expected);
}
}
You can now run the Homework for manual testing, or the HomeworkTest class for automatic testing.
You could get the original String in the Main-class and hand it to the second class to execute the for-loop. The second class then returns the reversed String so that the Main-Class can print it out.
The second class could contain a static method which reverses the String (executes the for-loop) or you can create an object of the second class and and this Object the original String to reverse.
There are several ways to do this. Most trivially, you could make a static function in a Test class, like so:
class Test
{
public static void runTest(String args[])
{
//same as your above program
}
}
But that is probably not what your teacher wants. Instead, you could make a Test class that reverses a set of strings.
class Test
{
public static void runTests()
{
//iterate through a list of hard-coded strings to test
}
}
You would then make a separate function in a Reverser class and the Test.runTests() function would test the Reverser class.
However, there are standardized ways of doing this. One common way is called JUnit. If you are using Eclipse, try this page for instructions.
The simplest way is to
Divide your code into a function public String reverse(String input)
Create new Tester class
Add test method in tester class public void test()
Prepare assertions to test your function assert reverse("ola").equals("alo") : "First assertion failed"
In main function run new Tester().test();
To make assertions working you have to run jvm with -ea option

Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1 [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.

Passing values from main class to other classes in Java

I'm on a project that requires passing values from main class to other classes. All of the classes are correctly working when they have their main functions. However, my project should have only one main class that calls other functions in other classes.
An example for main and another class is below. I want to scan the input through main class and pass it to parse class. Current implementation gives two error which are:
Exception in thread "main" java.lang.NullPointerException
at url.checker.Parse.GetInput(Parse.java:16)
at url.checker.Main.main(Main.java:14)
Java Result: 1
Given input: -url=google.com,-time=5,-email=asdfg#hotmail.com
Main.java:
package url.checker;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the parameters as '-url=' , '-time=' , '-email='.");
Parse.s = in.nextLine();
Parse.GetInput(Parse.s);
}
}
Parse.java:
package url.checker;
import java.util.Scanner;
public class Parse
{
static String s;
static String result[];
public static void GetInput(String s)
{
int i;
for(i=0;i<3;i++)
{
if (s.startsWith("-url="))
result[0] = s.substring(5, s.length());
else if (s.startsWith("-time="))
result[1] = s.substring(6, s.length());
else if (s.startsWith("-email="))
result[2] = s.substring(7, s.length());
else
System.out.println("You didn't give any input.");
}
}
}
Thank you very much for your help.
static String result[];
You never initialized the array; Since its a static it gets initialized to null by default.
Initialize using static String[] strings = new String[10];. This will hold 10 elements of String.

How to write a 3 class program and have the main class trigger methods in the other two

I have to write a program with 3 classes and lots of different methods.
I've written a simpler example to try and get an idea where I am going wrong
First class (music) is defining a music object with three data types. And should have a method to print the contents of an array.
the second class (musicArray) has all the data for the array and should build the array when the third class tells it too.
the third class(searchclass) has the main method it should tell the second class to make the array then with user input search the array for songs that match the rating.
import java.util.Arrays;
public class Music extends musicArray {
private String songTitle;
private double songLength;
private int rating;
static String everything;
public Music(String songTitle, double songLength, int rating) {
this.songTitle = songTitle;
this.songLength = songLength;
this.rating = rating;
}
public String getsongTitle()
{
return songTitle;
}
public double getsongLength()
{
return songLength;
}
public int rating()
{
return rating();
}
#Override
public String toString() {
return "music{"+ "songTitle= " + songTitle + ", songLength= "
+ songLength + ",rating=" + rating + '}';
}
public Music[] printsonglibrary(char[][] songDetails){
for (int count = 0; count <= 6; count++)
{
return System.out.println(songDetails[count]);
System.out.println(" ");
}
}
}
public class musicArray extends Searchclass{
static Music song1 = new Music ("achy breaky", 5.32, 10);
static Music song2 = new Music ("billy",1.2, 8 );
static Music song3 = new Music ("hello", 1.5, 9 );
static //Create array and make posistion 0 = song1
Music[] songDetails ={song1,song2,song3};
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
for(int count = 1; count <= songDetails.length; count++){
system out put for debugging
System.out.println(songDetails.length);
System.out.println(songDetails[count - 1]);}
}
/* public String songSeach(){
System.out.println("what rating of song do you want to search for?");
Scanner keyboard = new Scanner(System.in);
int searchValue = keyboard.nextInt();
if searchValue == rating in array use the printsonglibrary
method in the music class to print the array entry
*/
}
}
If I have the main method in the musicArray class I can print the array
So the question is how do I make the Songdetails array available in the seachclass?
You shouldn't directly expose any variables of one class to another. Instead consider giving the MusicArray class (note that by convention class names should begin with a capital letter) a public method, say public void printOutSongDetails() that would print out the contents of the array. Your main method can then call this method off of the MusicArray object that it has created. e.g.,
Edit 1
Also, the Music class should most definitely not extend the MusicArray class for there is no way that a Music object should behave like a MusicArray object. And on the same token, MusicArray should not extend the SearchClass.
Edit 2
Note that there are several other significant issues with your code that each one would prevent it from compiling, and this suggests that you should modify how you program (if you can't use an IDE). Try to compile early and often, and only add new code to the program after fixing any compilation errors so that the current code base compiles.
Edit 3
A small code example of what I was describing above.
class SearchClass {
public static void main(String[] args) {
MusicArray musicArray = new MusicArray();
musicArray.addMusic(new Music("Foobars Unit", 10.4, 5));
musicArray.addMusic(new Music("Spamalot", 11.0, 7));
//... etc ...
musicArray.printOutSongDetails();
}
}
Also, you'll probably not want those static Music variables but rather give MusicArray a method to add Music to its array, a public void addMusic method that accepts a Music object as a parameter.
One way is to make it public public Music[] songDetails ={song1,song2,song3};
A better way is to provide getter:
public Music[] getSongDetails() {
return songDetails;
}

Categories

Resources