Issue with recognizing methods - java

I'm a new coder and I'm having some trouble with my methods. I made a few but they aren't being detected in the main method. (P.S I havent filled most of the methods yet because I want to remedy the problem first.)
Thanks everyone.
package area;
import java.util.*;
/**
*
* #author domendes
*/
public class Area {
public static void main(String[] args) {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the area calculating code! Which shape would you like to calculate the area of?");
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit.");
int request = kbdln.nextInt();
if (request == 1) {
areaTriangle();
} else {
if (request == 2) {
areaCircle();
} else {
if (request == 3) {
areaRectangle();
} else {
if (request < 1) {
System.out.println("Goodbye");
return;
}
}
}
}
}
}
public static void areaTriangle() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the Tirangle area cacluator. Enter in the height of your triangle");
double triBase = kbdln.nextDouble();
}
public static void areaCircle() {
}
public static void areaRectangle() {}
}

In Java, everything is an object. So the methods that you are creating are actually methods which belongs to your Area class. If you want to access them you have to use Area class to refer to them.
Given that you have created static method (which means that your methods are at class level and not at object level. you should read more about it). You can access them using classname.methodname. In your case it would be Area.areaTriangle().

Your if/else statements are poorly structured. The first statement should be if, each statement following it should be elseif and the very last one should be else. However in this case a switch statement would be best
switch(request){
case 1:
areaTriangle();
break;
case 2:
areaCircle();
break;
case 3:
areaRectangle();
break;
default:
System.out.println("Goodbye");
}

they aren't being detected in the main method
The main method is a static context, which means if you are trying to call those methods from outside the Area class, you would have to do Area.areaTriangle(), for example.
Alternatively, you could define an AreaPrompter class, that would be like so.
Then, if you want to use those methods in any other class, you can do
AreaPrompter prompter = new AreaPrompter();
prompter.whateverMethodNameHere();
public class AreaPrompter {
public static void main(String[] args) {
AreaPrompter prompter = new AreaPrompter();
// main method
prompter.run();
// just the triangle method
prompter.areaTriangle();
}
public void run() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the area calculating code! Which shape would you like to calculate the area of?");
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit.");
int request = kbdln.nextInt();
if (request <= 0) {
System.out.println("Goodbye");
return;
} else if (request == 1) {
areaTriangle();
} else if (request == 2) {
areaCircle();
} else if (request == 3) {
areaRectangle();
}
}
public void areaTriangle() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the Tirangle area cacluator. Enter in the height of your triangle");
double triBase = kbdln.nextDouble();
}
public void areaCircle() { }
public void areaRectangle() { }
}

public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit."
int num = sc.nextInt();
if(num == 1){
areaTriangle();
}else if(num == 2){
areaCirlce();
}else if(num == 3){
areaRectangle();
else{
System.out.println("GoodBye");
}
There is nothing wrong with the way you calling your methods since the main method is static you can call the static methods directly without the use of any objects of class etc.

Related

Test Class with non static variable error message

I am a creating a testMethod() class below to test methods in the Main class. When I executed the program, it gave a compiler error: Java non static variable cannot be referenced from Non Static context. The project calls for 2 different classes constructed. The first class must consists of 3 methods, in which the third one calls for method 1 and 2. The second class is used to test methods in the main class.
I am new to Java, and I am struggling to figure out what causes this error.
Thanks
import java.util.Scanner;
public class Main {
char reply;
int input;
public void gradeModule(int mark) {
mark = input;
if (mark >= 70) {
System.out.println("Excellent");
} else if (mark >= 60 && mark <= 69) {
System.out.println("Good");
} else if (mark >= 50 && mark <= 59) {
System.out.println("Satisfactory");
} else if (mark >= 40 && mark <= 49) {
System.out.println("Compensatable fail");
} else {
System.out.println("Outright fail");
}
}
public int getValidModuleMark() {
Scanner keyboard = new Scanner(System.in);
while (input > 100 || input < 0)
{
System.out.println("Please enter a valid mark between 0 - 100: ");
input = keyboard.nextInt();
}
return input;
}
public void startModuleGrading() {
System.out.println("*********** Module Grading Program *********");
do {
getValidModuleMark();
gradeModule(input);
System.out.println("Would you like to continue grading (Y/N)? ");
Scanner keyboard = new Scanner(System.in);
reply = keyboard.next().charAt(0);
if (reply == 'N' || reply == 'n') {
System.out.println("Thank you!");
}
} while (reply == 'Y' || reply == 'y');
}
}
class testMethod {
Main test = new Main ();
public static void main(String [] args){
test.startmoduleGrading();
}
}
ANSWER TO ORIGINAL QUESTION:
Based on what i'm reading here, your teacher probably wants one class like this:
class X
{
public int methodOne(int i)
{
return i++;
}
public int methodTwo(int i)
{
return i--;
}
public int methodThree(int i)
{
return methodOne(i) + methodTwo(i);
}
}
Then you would have another class for testing:
class Tester
{
public static void main(String[] args)
{
X test = new X();
System.out.println(test.methodOne(3));
System.out.println(test.methodTwo(3));
System.out.println(test.methodThree(3));
}
}
This shows that you made the class and that the methods work.
ANSWER TO UPDATED QUESTION:
In your code, you have declared the Main test = new Main ();
outside of your main method, which is indeed a static method. Move the declaration inside of the method and everything should work. Thus, your program should look like this:
public static void main(String [] args)
{
Main test = new Main ();
test.startmoduleGrading();
}

Memory Calculator confusion java

In my class we needed to make a memory calculator in Java. Im really new to Java and had help making the program. Turned it in and the teacher said "Please separate the MemoryCalculator class from the class with the main() method. Currently the way you have created the class, there is no reason to create an instance of the class. But the point of the assignment is to use separate classes and objects." Its been a super long week and midterms and just lost at this time. Any help would be great.
import java.util.Scanner;
public class MemoryCalculator {
private double currentValue;
//Methods
//Scanner
public static int displayMenu(){
Scanner input = new Scanner(System.in);
System.out.print("Lets do some math! \nMenu \n1. Add \n2. Subtract \n3. Multiply \n4. Divide \n"
+ "5. Clear \n6. Quit \n\nWhat would you like to do? ");
int menuChoice = input.nextInt();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System. in );
double operand;
System.out.println(prompt);
operand = input.nextDouble();
return operand;
}
//Current Value
//Gets
public double getCurrentValue() {
return currentValue;
}
//Setter
public void setCurrentValue(double currentValue) {
this.currentValue = currentValue;
}
//Add
public void add(double operand2) {
currentValue += operand2;
}
//Subtract
public void subtract(double operand2) {
currentValue -= operand2;
}
//Multiply
public void multiply(double operand2) {
currentValue *= operand2;
}
//Divide
public void divide(double operand2) {
if (operand2==0){
setCurrentValue(0);
}
currentValue /=operand2;
}
//Clear
public void clear() {
currentValue = 0;
}
//Main part of the calculator
public static void main(String[] args) {
MemoryCalculator instance = new MemoryCalculator();
double operand;
boolean repeat = true;
while (repeat) {
System.out.println("The current value is: " + instance.getCurrentValue() + "\n");
int menuChoice;
menuChoice = displayMenu();
if (menuChoice > 6 || menuChoice < 1){
System.out.println("I'm sorry, " + menuChoice + " wasn't one of the options\n");
}
switch(menuChoice){
case 1:
operand = getOperand("What is the second number?");
instance.add(operand);
break;
case 2:
operand = getOperand("What is the second number?");
instance.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?");
instance.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?");
instance.divide(operand);
break;
case 5:
instance.clear();
break;
case 6:
System.out.println("Goodbye have a great day");
System.exit(0);
break;
}
}
}
}
What it looks like you did with your program was create one, single, class that holds all of the code for your calculator program, within which you instantiated an object of the same class.
What your teacher wants instead, is for you to have two separate classes, one which contains the code that makes the calculator work, and another class where you instantiate an object of the first class, and call the methods contained within that class.
For your assignment, what I would suggest would be to create a new class, perhaps called Main, where your program's Main() method will be, and keep all of the code for the calculator program in the MemoryCalculator class. From there, you can instantiate an object of MemoryCalculator class (which you already did, called instance) and use method calls to reference methods and attributes from within the MemoryCalculator class.
This may require reworking some of your code so that it runs properly, given that you'll be calling most of it from an object of the MemoryCalculator class, but it should be doable.

how to get data from other methods?

does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}

Avoid resetting integer variable

I'm making a game in Java where you have to take care of a dog. I made my game method call itself so that I won't have to copy and paste the contents in this method several times. The problem is that I don't know how to go around the two integer values I declared, because the integer values are added and subtracted through each choice and calling the method again will change those changed values back to default.
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static void main(String[] args) {
game();
}
public static void game() {
Integer diet;
diet = 5;
Integer happiness;
happiness = 10;
System.out.println("");
System.out.println("Dog \t Hunger: " + diet
+ "\n \t Happiness: " + happiness);
System.out.println("");
System.out.println("1. Feed \n2. Play \n3. Ignore");
System.out.println("");
System.out.print("> ");
String input = kybd.nextLine();
if (input.equalsIgnoreCase("1")) {
diet++;
game(); // This is supposed to go to the
// beginning with the changed value of diet.
} else if (input.equalsIgnoreCase("2")) {
happiness++;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else if (input.equalsIgnoreCase("3")) {
happiness--;
diet--;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else {
System.out.println("Invalid Input");
game(); // This is supposed to go the beginning
// where you can change your input but
// still has your changed values.
}
if (diet <= 0);
{
System.out.println("Your dog died because it did not eat.");
game(); // This is supposed to go to the beginning
// with the default values.
}
if (diet > 10);
{
System.out.println("Your dog died because it was overfed.");
game(); // This is supposed to go to the
// beginning with the default values.
}
if (happiness <= 0);
{
diet--;
System.out.println("Your dog is no longer happy. He will not eat.");
}
{
if (happiness > 10);
System.out.println("Your dog died because it was too excited.");
game(); // This is supposed to go to the
// beginning with the default values.
}
}
}
If I understand your problem in a right way, the only thing you have to do is declare these two variables as class variables (static or not). So the final code is:
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static int diet = 5;
public static int happiness = 10;
public static void main(String[] args) {
game();
}
Regards
EDIT FOR DOG DIE
public static die() {
diet=5;
happiness=10;
}
Call this function everytime you that your dog die before call game().

Globalize an input variable in Java

I am trying to make a lottery game in Java and it uses method calls instead of while loops for looping purposes. However, I cannot get an input variable( such as int bet = input.nextInt()) to be recognized as a variable for other methods. I do not know how to globalize "bet" so it can be used by all the methods instead of just in the method it is a part of. Here is part of my code below, including just the one method called "play()"
public static void play()
{
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
int play = input.nextInt();
if(play == 1)
{
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
int bet = input.nextInt();
if((bet <= account) && (bet > 0)){
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}
Simplest answer is to declare play and bet as static class variables.
public class Game {
private static int play = 0;
private static int bet = 0;
public static void play() {
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
play = input.nextInt();
if(play == 1) {
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
bet = input.nextInt();
if((bet <= account) && (bet > 0)) {
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}
Define bet outside of the play() method.
If you define bet as a field in the class like :
public class Lottery {
private int bet;
public void lottery() {
...
}
public void play() {
...
}
public static void main(String[] args) {
Lottery lottery = new Lottery();
lottery.play();
}
}
then bet is available in all methods in the class, but not outside.
It is not necessary to make play public, so this can stay nicely inside the scope of the play method. It is considered good practice to give variables no more visibility than strictly needed.
Most people would in this case not make bet a field, but pass it as a parameter to the lottery method. In this case the visibiltiy can even be further restricted to only the play and lottery methods.
A final note is you use of function calls to loop. Since java does not support tail-call-optimisation (and it would not apply here in any case) you are going to fill up the stack and finally die of a stack overflow if you play long enough.
Pass it between methods as a parameter. (Defining it as public is not recommended.) Or, if this is a class, you can make it a member variable (property).

Categories

Resources