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();
}
Related
So I was given the following GradedActivity class:
public class GradedActivity
{
private double score; // Numeric score
public void setScore(double s)
{
if (s < 0)
score = 0.0;
else if (s > 100)
score = 100.0;
else
score = s;
}
public double getScore()
{
return score;
}
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
} }
and I was tasked with generating a constructor that accepts values for points Obtaned and pointsTotal as arguments, initializes them, and sets the corresponding score (points obtained divided by points total), accessors and mutators for pointsobtained and total.
So here is what I came up with:
public class ProgrammingAssignment extends GradedActivity
{
public int pointsObtained;
public int pointsTotal;
public ProgrammingAssignment(int p, int t)
{
pointsObtained = p;
pointsTotal = t;
}
public int getPointsObtained()
{
return pointsObtained;
}
public int getPointsTotal()
{
return pointsTotal;
}
public double getScore()
{
return pointsObtained / pointsTotal;
}
public void setPointsObtained(int p)
{
pointsObtained = p;
}
public void setPointsTotal(int t)
{
pointsTotal = t;
}
}
Everything compiles without error, but getScore isn't computing obtained/total (it comes back 0) in my test class:
public class PADemo
{
public static void main(String[] args)
{
ProgrammingAssignment p1 = new ProgrammingAssignment(28,30);
GradedActivity p2 = new ProgrammingAssignment(0,30);
System.out.println (p1.getPointsObtained());
System.out.println (p1.getPointsTotal());
System.out.println (p1.getScore());
System.out.println (p1.getGrade());
System.out.println (p2.getScore());
System.out.println (p2.getGrade());
p1.setPointsObtained(25);
p1.setPointsTotal(40);
System.out.println (p1.getScore());
System.out.println (p1.getGrade() == 'F');
}
}
How do I obtain the score (points obtained/points total) with getScore()
Test class returns:
28
30
0.0
F
0.0
F
0.0
true
Cars waiting: [a A123TR, a Z23YTU, a R23EWQ, a ERW345, a B12GFT...
Does that look correct? Why would you have the "a " at the beginning? That is not part of the car license. The "a " and "d " need to be removed BEFORE you add the license to the garage or queue.
creates a stack for cars in a garage (Max of 7)
a queue for cars waiting (max of 5)
Your basic logic appears wrong (to me).
When you get an "a" you do one of two things:
if there are less than 7 cars in the garage you add the car to the garage.
If there are 7, then if then are less the 5 cars in the queue, you add the car to the "queue".
When you get a "d" you:
first remove the car from the "garagee",
then you check the "queue". If there are cars in the "queue" then you move the car from the "queue" to the "garage".
So the logic might be structure something like:
while (...)
{
...
String[] data = line.split(" ");
if (data[0].equals("a"))
processArrival( data[1] );
else if (data[0].equals("d"))
processDeparture( data[1] );
}
I used the String.split(...) method which was suggested in your last question because it is a better test then to test the whole String for a specific character and your two pieces of data are separated into the array ready for processing. The data will now be split into two pieces of data: a) function
b) license
I used separate methods because the code is easier to read and logic for each function is contained in individual methods.
I know it's very basic java but I am trying to learn. Can someone help me to understand my errors and what should I do to solve it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int teamA = 0;
int teamB = 0;
//asks for the team selection
System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B");
Scanner input = new Scanner(System.in);
int result = input.nextInt();
public String scoreBoard() {
String displayScoreBoard = "No Score";
if (result.toString == "A" || result.toString == "a"){
teamA++;
displayScoreBoard = "Score of TeamX is" + teamA;
} else if (result.toString == "B" || result.toString == "b"){
teamB++;
displayScoreBoard = "Score of TeamY is" + teamB;
} System.out.println(displayScoreBoard.toString);
}
// write your code here
}
}
You made several mistakes. For example you wrote a function within a function. You better don't do that. Just look at my code. If you have any questions, just ask ;)
UPDATE: Due to the comments that there should be a loop, I've adapted the code.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int teamA = 0;
int teamB = 0;
//asks for the team selection
while(true) {
System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B. Type anything else to quit.");
Scanner input = new Scanner(System.in);
String result = input.next();
if (result.toUpperCase().equals("A")) {
System.out.println("Score of TeamX is" + ++teamA);
} else if (result.toUpperCase().equals("B")) {
System.out.println("Score of TeamY is" + ++teamB);
}
else {
break;
}
}
}
}
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.
My student grade classifier needs to use the returned values, and I have tried but the input is prompted for three times. I'm sure this is because I'm calling the method getStudentMark() to use the retrieved value from that method.
Code:
public static int getStudentMark()
{
Scanner in = new Scanner(System.in);
System.out.println("Exam Mark :> ");
int mark = in.nextInt();
return mark;
}
public static String getStudentFinalGrade()
{
int studentGradeMark = getStudentMark();
String studentGrade = "";
int studentGradeMark = getStudentMark();
if (studentGradeMark >= 90) {
return "A";
} else if (studentGradeMark >= 80) {
return "B";
} else if (studentGradeMark >= 70) {
return "C";
} else if (studentGradeMark >= 65) {
return "D";
}
return "F";
return studentGrade;
}
public static void printGrade()
{
System.out.println("Your Grade is" + getStudentFinalGrade());
}
Then calling these in the main method (which I cannot change):
public static void main(String[] args) {
getStudentMark();
getStudentFinalGrade();
printGrade();
}
Where am I going wrong when assigning the int?
It keeps asking for an input 3 times. Then works on the third attempt
to get an input grade. Just read nextLine, use a regular expression to see it's a number and the use Integer.parseint(String grade) to get the final grade.
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).