Method is undefined error - java

I am trying to write a code that uses a menu to call on a method in a different file that is in the same folder.
import java.util.Scanner;
public class BugTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("==Bug Solution==");
System.out.println("Enter the bug's intial position: ");
int pos = input.nextInt();
Bug bug = new Bug(pos);
System.out.println("--Menu--");
System.out.println("1) Change Directions");
System.out.println("2) Move Bug");
System.out.println("3) Exit");
int menu = input.nextInt();
while (menu != 3) {
switch(menu) {
case 1: turn();
break;
case 2: move();
break;
default: System.out.println("Invalid Response");
break;
}
menu = input.nextInt();
}
}
}
I get an error on case 1 and case 2 saying the method is undefined for type BugTest.

In a main method you should always call methods from a given Object (given that they are not static methods). Otherwise the program doesn't know which object's method it's supposed to call. For example create class Bug:
public class Bug{
public Bug() {
}
public void moveLeft() {
// add code here
}
}
Then in your main method call the method by creating an instance of class Bug:
public static void main(String[] args) {
Bug myBug = new Bug();
myBug.moveLeft() ; // calls the method of the myBug object
}
In your case the problem can be solved by calling bug.turn() and bug.move() instead of just turn() and move().

Related

Can I check the local vairable by using method in other class?

public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}

Java and ArrayLists

package test.arraylist;
import java.util.Scanner;
public class TestArraylist {
static Scanner keyboard = new Scanner (System.in);
static int how_many;
public static void main(String[] args) {
menu();
}
public static void menu()
{
System.out.println("1.L2C");
System.out.println("2.M2R");
int menu = keyboard.nextInt();keyboard.nextLine();
switch (menu){
case 1:
NewClass l2c = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.l2c.add(keyboard.nextLine());
System.out.println("values:"+l2c.getL2c());
}
break;
case 2:
NewClass r2p = new NewClass();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.getR2p());
}
break;
}
}
public static void seats(){
System.out.println("values:"+r2p.getR2p()); // Error
System.out.println("values:"+l2p.getR2p()); // Error
}
}
---------------------------CLASS-----------------------
package test.arraylist;
import java.util.ArrayList;
public class NewClass {
ArrayList<String> l2c = new ArrayList<>();
ArrayList<String> r2p = new ArrayList<>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
I'm in java for only 2 weeks
In a few words, I'm going to explain what I'm trying to do.
I am creating an ArrayList, after this user is entering
values to Arraylist.
Once everything is done, I want to access data from another method and to make some math operations, I realized that I should use some sort of return, I have tried to do this, but it does not work.
I am definitely doing something wrong.Pls help to sort this out.I spent 2 days on this.
It seems what you need is the composition of the NewClass into your Main class i.e.TestArraylist , Read composition in java composition-in-java-example
Now your code should be like this,
public class TestArraylist {
static NewClass newClass = new NewClass();
---------
--------
public static void menu(){
case 1:
ArrayList<String> l2c = newClass.getL2c(); //this way you can access the data
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
l2c.add(keyboard.nextLine()); //here you need only the instance variable to add the data into the arraylist.
System.out.println("values:"+l2c.toString()); //to print the data
}
break;
//Same way you should modify the case2 as well.
case 2:
ArrayList<String> r2p = newClass.getR2p();
System.out.println("How many:");
how_many = keyboard.nextInt();keyboard.nextLine();
for (int i=0;i<how_many;i++){
System.out.println("Insert values:");
r2p.add(keyboard.nextLine());
System.out.println("values:"+r2p.toString());
}
break;
Now that composite object will be accesible in you below method because we have declared it static.
public static void seats(){
System.out.println("values:"+newClass.getR2p()); // not throw any error
System.out.println("values:"+newClass.getR2p()); // not throw any error
}
Also your Newclass should be defined like this,
public class NewClass {
private ArrayList<String> l2c = new ArrayList<String>();
private ArrayList<String> r2p = new ArrayList<String>();
public ArrayList<String> getL2c() {
return l2c;
}
public void setL2c(ArrayList<String> l2c) {
this.l2c = l2c;
}
public ArrayList<String> getR2p() {
return r2p;
}
public void setR2p(ArrayList<String> r2p) {
this.r2p = r2p;
}
}
There are many things to be corrected but as of now to make your programm work , this should suffice.
If you call seats(), you will have an error because those variables are not declared within the proper scope. To make r2p and l2c available within that method, move the variable declarations outside of the method (below the class declaration, before main()) with the initializer private static NewClass newClass;. Feel free to assign a value as needed, or employ optionals (but considering you’ve only been doing Java for 2 weeks, stay away from optionals; just make sure you assign a value).
Edit: Use static modifier on the variables, since you’re accessing from a static context.

Java accessing another class not working

I am making a game that requires an update class to access a game class and a main class to access both of those. The problem I am having is that I need the update class to have an updated object of the game class but I get an error whenever I try and access the game class from the Update class [error occurs on newGame.test();]
ERROR: Exception in thread "main" java.lang.NullPointerException
at Updates.updateStats(Updates.java:17)
at Game.gameLoop(Game.java:24)
at Main.main(Main.java:14)
import java.util.Scanner;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Game newGame = new Game();
//Updates getUpdates = new Updates();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
import java.util.Scanner;
public class Game {
static Scanner input = new Scanner(System.in);
Updates getUpdates = new Updates();
public Game(){
}
String goverment;
int happyness;
double money;
int population = 1000000;
public static boolean isRunning;
private int turn = 0;
public void gameLoop(){
while (isRunning){
getUpdates.updateStats();
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
public void setupGame()
{
System.out.println("Goverment: 1=Democracy 2=monarchy 3=dictatorship");
goverment = input.nextLine();
while (!goverment.equals("1")||!goverment.equals("2")||!goverment.equals("3")){
if (goverment.equals("1")){
happyness = 75;
money = 250000.0;
break;
}
else if (goverment.equals("2")){
happyness = 50;
money = 500000.0;
break;
}
else if (goverment.equals("3")){
happyness = 25;
money = 750000.0;
break;
}
else{
System.out.println("ENTER A VALID VALUE");
goverment = input.nextLine();
}
}
System.out.println("1");
}
public int getHappyness(){
return happyness;
}
public void test(){
System.out.println("MY NAME IS BOB");
}
}
import java.util.Scanner;
public class Updates {
static Scanner input = new Scanner(System.in);
public Updates(){
}
public Updates(Game newGame){
this.newGame = newGame;
}
Game newGame;
public void updateStats(){
newGame.test();
}
}
I'm sorry if this isn't very much help, but it's my first time answering a question on here.
I put your code into a test project to see where the issue was, and it seems you have a few errors.
I'll start with the Main class as it has the smallest issues.
You don't need to declare the scanner object here as it's never used. You're just allocating memory to an empty object.
Now, onto the Updates class.
Again, no need to declare a scanner here.
To use the object "newGame" you need to make sure you're making use of the Constructor:
public Updates(Game newGame){
this.newGame = newGame;
}
And not:
public Updates(){
}
Because the latter one won't set the Game object for you, and any time you access it you will get a nullpointer.
Finally, the Game class:
I'd make both the Scanner and the Updates objects private, as they're never used outside the class. If they are, make use of getters and setters.
In your Game constructor, you can actually create both the getUpdates and input objects, like so:
public Game() {
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
That way whenever your game is initialized, you'll have them at the ready. As you can see, I put
new Updates(this)
which uses the Updates constructor I mentioned before. This should ultimately solve your issue.
For reference, here are the files I used/edited and it worked on my end:
Pastebin link

Java Coding--Inheritance Issues

I am new to java and am having a lot of issues making a multilevel inheritance program.
I'm trying to make a program where my main class (AU) is broken down into subclasses depending on what the user types.
My issue is when I try to call my second level (Part_Time_Student) subclass from my first level subclass (Student).
Whenever I try to call it, it just recalls the first level subclass(the one I'm currently in).
I noticed that if I make my second level subclass(Part_Time_Student) extend the main superclass(AU) it works, but I would prefer to make it extend student.
I realize this is a very complicated post (especially since I don't know the terminology), but I hope my code is easy enough to follow.
AU.java
public class AU {
Scanner input;
static String name;
static Long numb;
public AU() {
}
public void Name() {
input=new Scanner(System.in);
System.out.println("What is the member's name");
String nam = input.nextLine();
AU.name=nam;
System.out.println(nam +" has been added");
}
public void Phone() {
input=new Scanner(System.in);
System.out.println("What is the member's phone number");
Long number = input.nextLong();
AU.numb=number;
System.out.println(number+ " has been saved");
}
}
Main.java
public class Main {
private static Scanner input;
public static void main(String[] args) {
AU au = new AU();
au.Name();
au.Phone();
while (3==3) {
System.out.println("What is your role at the University?");
input=new Scanner(System.in);
String determ=input.nextLine();
if (determ.toUpperCase().equals("STUDENT")) {
Student student=new Student();
break;
}
else if (determ.toUpperCase().equals("STAFF")) {
break;
}
else if (determ.toUpperCase().equals("FACULTY")) {
break;
}
else if (determ.toUpperCase().equals("TESTER")) {
break;
}
else {
System.out.println("Invalid Response");
}
}
System.out.println("yay");
}}
Part_Time_Student.java
public class Part_Time_Student extends Student {
public Part_Time_Student() {
System.out.println("it switched");
System.out.println(GPA);
System.out.println(Assign);
System.out.println(name);
}
public void tester() {
System.out.println("test");
}
}
Student.java
public class Student extends AU {
static double GPA=5;
static String Assign;
public Student() {
super();
System.out.println(name);
System.out.println("Are you a full-time student or part- student(type part or full)");
input=new Scanner(System.in);
while (3==3) {
String get=input.nextLine();
switch (get.toUpperCase())
{
case "PART":{
Student.Assign="Part";
Part_Time_Student Studentp = new Part_Time_Student();
break;
}
case "FULL":{
Student.Assign="Full";
break;
}
default :{
System.out.println("Invalid ");
}}}
}
public void gpa(String grade,long credits) {
System.out.println(name+numb);
name=name;
}
public void Welcome() {
System.out.println("Welcome Student");
}
}
Output:
What is the member's name
-Test
Test has been added
What is the member's phone number
-540
540 has been saved
What is your role at the University?
-student
Test
Are you a full-time student or part-student(type part or full)
-part
Test
Are you a full-time student or part-student(type part or full)
As you can see the command "Part_Time_Student Studentp = new Part_Time_Student();" is just recalling the student class over an over.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Move your statement Part_Time_Student Studentp = new Part_Time_Student(); out of while loop, infact out of the constructor.
When you are constructing your Student class, and inside when you invoke a constructor of subclass, it in turn calls its super class which is Student, so it goes over and over. So it will keep asking you same question again and again.
Remove the Part_Time_Student constructor from :
case "PART":{
Student.Assign="Part";
// Part_Time_Student Studentp = new Part_Time_Student(); //remove this
break;
}
Change this if condition in your Main class below to:
if (determ.toUpperCase().equals("STUDENT"))
{
Student student=new Student();
if ( student.Assign.equalsIgnoreCase( "Part" ) )
{
Part_time_Student part_time_student = new Part_time_Student();
}
break;
}

Method that displays a GUI Window

import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
public class PictureViewer {
final static int MIN_NUMBER = 1;
final static int MAX_NUMBER = 8;
static int image_number = 1;
public static void main(String[] args) {
showMenu();
}
public static int forward(int current_number) {
if (current_number < MAX_NUMBER) {
current_number++;
} else {
current_number = MAX_NUMBER;
}
return current_number;
public static int backward(int current_number) {
if (current_number > MIN_NUMBER) {
current_number--;
}
return current_number;
}
public static String createFileName(int current_number) {
return ("Picture " + current_number + ".jpg");
}
public static String createRandomName() {
return ("Picture " + (int) (Math.random() * 8 + 1) + ".jpg");
}
public static void showMenu() {
PictureViewer theobject = new PictureViewer();
int current_number = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Choose static forward(1), static backward(2),"
+ " createFileName(3), createRandomName(4)");
int user = input.nextInt();
switch (user) {
case 1:
System.out.println("static forward");
current_number = forward(current_number);
theobject.forward();
break;
case 2:
System.out.println("static backward");
current_number = backward(current_number);
theobject.backward();
break;
case 3:
System.out.println("createFileName");
createFileName(current_number);
theobject.showWindow(createFileName(current_number));
break;
case 4:
System.out.println("createRandomName");
createRandomName();
theobject.showWindow(createRandomName());
}
if (image_number != 1);
System.out.println(image_number);
}
}
public void forward() {
if (image_number < MAX_NUMBER) {
image_number++;
} else {
image_number = MAX_NUMBER;
}
}
public void backward() {
if (image_number > MIN_NUMBER) {
image_number--;
}
}
public void showWindow(String filename) {
JFrame frame = new JFrame("GUI Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
What I'm supposed to do:
Write a new function to create and display a GUI window (which I did by doing the showWindow method but I'm not sure how to code the rest of it).
In your switch statement, where you call the methods createFileName() and createRandomName(), add calls to object.showWindow() and pass it the file name the methods return (I added object.showWindow() to those particular methods but I'm getting errors). Test your program, you should be able to go forward and backward with proper behavior when MIN_NUMBER and MAX_NUMBER are reached. When the window is displayed the correct file name should be shown at the top of the frame.
Areas of interest:
Here
case 3:
System.out.println("createFileName");
createFileName(current_number);
theobject.showWindow();
break;
case 4:
System.out.println("createRandomName");
createRandomName();
theobject.showWindow();
and here
public void showWindow(String filename) {
}
First, the compile errors in your program. I copied and pasted your code to my IDE and in the object.showWindow() lines I get compile errors it says:
method showWindow in class PictureViewer cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
To a Java beginner, this may seem cryptic, however it just tells you that the method you are calling, in this case the showWindow() method, is requiring you to pass a String but you are not passing anyting that's why it throws an error. Also, in your question you said
call the methods createFileName() and createRandomName(), add calls to object.showWindow() and pass it the file name the methods return
It is very clear now what to do to remove the compile errors. You need to pass the methods createFileName() and createRandomName(). After doing so, it will look like this:
case 3:
System.out.println("createFileName");
theobject.showWindow(createFileName(current_number));
break;
case 4:
System.out.println("createRandomName");
theobject.showWindow(createRandomName());
Next is the creating and displaying the GUI Window. I will show you how to do this in pseudocode first so you will learn how to do it yourself.
First, add a global variable that we will use to refer to the window. Then, in the showWindow() method:
public void showWindow(String filename) {
if window is null
initialize new window
set the window title using filename
show window
else
set the window title using filename
}

Categories