Not able to resolve object error in bluej - java

getting error that variable not found. not able to figure out exact problem. tried resetting preferences also in bluej.
import java.util.*;
class Electricity
{
public void Initialization()
{
int omr = 0;
int nmr = 0;
int cr = 0;
int rent = 0;
double cost = 0.0;
double sc = 0.0;
}
public void input()
{
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
}
public void calculate()
{
cr = nmr - omr;
}
public static void main()
{
Scanner sc = new Scanner(System.in);
}
}

This is not error in bluej it's problem with the code
I'm guessing you are a student
The code is not working since variable only exist inside the method it was created in
You are trying to access variable defined in different methods.
Inside the input() method you trying to access variable that you defined in Initialization() method But it does not exist in input()
Jest to make this code work put all your code inside the main() method .
Or pass the method the variables they using from another method and of course you need to call those methods from main method but seems like you have some more learning to do to make the second option to work.
Good luck.

Somthing like that.
import java.util.Scanner; // Import the Scanner class
public class Main
{
static int calculate(int nmr, int omr)
{
int cr = nmr - omr;
return cr;
}
public static void main(String[] args)
{
int omr = 0;
int nmr = 0;
// int cr = 0;
// int rent = 0;
// double cost = 0.0;
// double sc = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
System.out.println("The resaults: " + calculate(nmr, omr));
}
}

Related

How to pass variables from one method to another?

Trying to write a grade calculator program and am running into problems passing return variables from one method to another. I'm new to coding so I'm sure this isn't very pretty, but was hoping to get some help.
I have a method to calculate the Homework score, a method to calculate the midterm score, and a method to calculate the final score. I'm trying to call the return variables in the last method to calculate overall grade. The error is when calling the courseScore method, and displays as: The method courseScore(int, int, int) in the type GradeCalc is not applicable for the arguments (). Any help is appreciated!
import java.util.*;
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int overAll;
int midtermScore;
int finalsScore;
hwpoints();
midTerm();
courseScore();
}
public static int hwpoints() {
int x;
int hwTotal = 0;
int pointsPossible = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of assignments:");
x = input.nextInt();
for(int i = 1; i <= x; i++) {
System.out.println("Enter assignment score:");
int hwScore = input.nextInt();
hwTotal += hwScore;
System.out.println("Enter total possible points:");
int points = input.nextInt();
pointsPossible += points;
}
int overAll = (hwTotal / x);
System.out.println("You got " + hwTotal + " out of " + pointsPossible + ". Your overall Homework grade is a: " + overAll);
return overAll;
}
public static int midTerm() {
int midtermPoints;
int midtermPossible;
int midtermScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Midterm Score:");
midtermPoints = input.nextInt();
System.out.println("Enter total possible Midterm Points:");
midtermPossible = input.nextInt();
midtermScore = (midtermPoints / midtermPossible);
System.out.println("Your Midterm score is " + midtermScore);
return midtermScore;
}
public static int finalScore() {
int finalsPoints;
int finalsPossible;
int finalsScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Finals Score:");
finalsPoints = input.nextInt();
System.out.println("Enter total possible Finals Points:");
finalsPossible = input.nextInt();
finalsScore = (finalsPoints / finalsPossible);
System.out.println("Your Finals score is " + finalsScore);
return finalsScore;
}
public static void courseScore(int finalsScore, int midtermScore, int overAll) {
Scanner input = new Scanner(System.in);
System.out.println("What percent of your grade is the final?");
int testWeight = input.nextInt();
System.out.println("What percent of your grade is the midterm?");
int midtermWeight = input.nextInt();
System.out.println("What percent of your grade is the homework?");
int hwWeight = input.nextInt();
int testWeighted = (finalsScore * (testWeight / 100));
int midtermWeighted = (midtermScore * (midtermWeight / 100));
int hwWeighted = (overAll * (hwWeight / 100));
int courseScore = ((hwWeighted + midtermWeighted + testWeighted) * 100);
System.out.println("Your total course grade is " + courseScore);
}
}
The methods hwpoints, midTerm and finalScore all return an int value which you are not keeping
You need to do some thing like
int hwp = hwpoints ();
int mt = midterm ();
int fs = finalScoare ();
then you can pass these variable into courseScore as
courseScore (fs, mt, hwp);
Note
In this code
int testWeighted = (finalsScore * (testWeight / 100));
you are going to be undertaking integer division.
See Int division: Why is the result of 1/3 == 0?
First thing is to understand the concept of a class and a static method.
Classes have fields and methods.
Fields (variables) hold data (state) that the Methods can operate on
Each instance of a class has its own values for these fields
Methods operate on the Fields
Methods can include call parameters
Methods can also return a value
Static instances (classes, fields, and methods) are singletons
There is only one copy of them (all instances of the class share the same one)
Static Methods cannot access (non-static) fields/methods
Using this, consider creating another class that has (most) of the content of your GradeCalc class and remove the statics from them and create an instance of that class in GradeCalc. That way each method in the class can access the fields you have defined.
Here is an example of the concept based on what you have already written.
Note: You code has other structural/implementation issue and I would never implement it as shown; but, I don't want to turn this into a Java course; so, I tried to show you something that could work within the context of what you had written.
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calc = new Calculator (calc);
calc.hwpoints();
calc.midTerm();
calc.courseScore();
int overAll = calc.OverAll;
int midtermScore = calc.MidtermScore;;
int overAll = calc.OverAll;
}
public class Calculator {
public void OverAll;
public void MidtermScore;
public void FinalsScore;
public void hwpoints()
{
...
OverAll = overAll
}
//Do the same for the methods below
//public void midTerm();
//public void courseScore();
}

How to call another method inside of the main method?

I am trying to call a method, readAndFill(); in my main method. I am getting an error message saying " readAndFill cannot be applied to given types. readAndFill is a method to just put numbers into an array.
I've renaming the method, putting readAndFill(double[]array, int numOfNumbers) instead of readAndFill();.
package program9;
import java.util.Scanner;
import java.util.Arrays;
public class Program9 {
static void readAndFill(double[]array, int numOfNumbers) {
Scanner keyboard = new Scanner(System.in);
for(int i=0;i < numOfNumbers; i++){
System.out.print("Enter a number: ");
array[i] = keyboard.nextDouble();
}
}
public static void main(String[] args) {
int numOfNumbers;
Scanner keyboard = new Scanner(System.in);
double arrayNumbers;
System.out.print("How many numbers will be read in the array?:
");
numOfNumbers = keyboard.nextInt();
double[] array = new double[numOfNumbers];
readAndFill();
}
static void readAndFill(double[]array, int numOfNumbers) {
Scanner keyboard = new Scanner(System.in);
for(int i=0;i < numOfNumbers; i++){
System.out.print("Enter a number: ");
array[i] = keyboard.nextDouble();
}
}
readAndFill methods need two parameter.
Replace the method call in main() with below.
readAndFill(array , numOfNumbers);
call your function this way readAndFill(array , numOfNumbers);

Create a simple java random number pick with in a certain range

I tried searching on here for something similar, but failed to find it, maybe using wrong keywords let me know, but here is the deal.
I am fairly new with java and wanted to make something useful myself.
My idea was to create a random number picker within a range with.
So let's say range is from 1-50, and I want 5 random number in this range, and they have to be all different. I have worked with Random before, but not sure what I am doing wrong, here is the code I have so far, please push me in the right direction if possible.
I want to create an array or list with the number, or is there a better way to do this?
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
rnd(start,end);
int[] randomArrays = new int[c];
for(int i = 0; i>randomArrays.length; i++){
randomArrays.add();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
sorry if my code is messy.
At the moment I can't even get the random number to be added into the array
Try this, I did explain to you what is wrong with comments at the code, read them.
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static int[] randomArrays; // You need to declare the vector as an instance variable, otherwise it will disappear when the method it's done.
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
randomArrays = new int[c];
for(int i = 0; i<randomArrays.length; i++){ // The condition was wrong
int numberToAdd = rnd(start,end);
randomArrays[i] = numberToAdd; //You are not using an ArrayList, vector has not the method add(), you have to add new element to the vector throughout its index
}
}
public static void main(String[] args) {
Randomizer rdm = new Randomizer();
rdm.nPicker();
for(int number:rdm.randomArrays) {
System.out.println(number);
}
}
}
Thank you everyone for your advices and hints. In the end I think I managed to get the code how I wanted with the code below.
Tell me if you see an error in this method, or if it has a way that is not allowed in java.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
List randomnumbers = new ArrayList();
for(int i = 0; i<c; i++){
int numb = rnd(start,end);
if(randomnumbers.contains(numb)){
break;
}else{
randomnumbers.add(numb);
}
}
randomnumbers.forEach(System.out::println);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
ok in the end i changed the loops as following:
for(int i = 0; i<c;){
int numb = rnd(start,end);
while(!(randomnumbers.contains(numb))){
randomnumbers.add(numb);
i++;
}
}
randomnumbers.forEach(System.out::println);
}
seems to work fine this way

Use Variable Which is in main method in Another Method

I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this
Here's my code
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
The problem I'm facing is that in the Loop method, I am unable to use the variable n
Is there a way to use a variable which is in the main method, in another one?
Ty
-Pingu
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
simply pass it as parameter:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n);
}
public static void Loop (int count)
{
for (int counter = 1; counter <= count; counter++)
{
System.out.println("*");
}
}
Pass it as a paramteer
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
loop(n); // added this
}
public static void loop (int n) // changed here
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
I think you should use it as a instance variable and for better understanding name your class like StarClass it can provide better understanding. Good programming practice.
But you should avoid unneccesserily making instance variable without any logic behind it.
I also think you could declare n as a public variable.
That should make it accessible throughout the code.
public int n;
But I guess that passing it as parameter is a better practice, since you don't create a deppendance inside your code. What I mean is, if something changes with the variable you break the function. It's good practice to always keep things "modular" in your code, so it makes it more resilient to changes and debugging.
It's better if you get used to it from the beggining =)
Two ways.. one has been posted already as answer and the other one would be using the variable as a field. This way you can access (and modify) it in every method without having to pass it on.
public class Alpha
{
static int n;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of stars");
n = input.nextInt();
loop();
}
public static void loop ()
{
for (int counter = 0; counter < n; counter++)
{
System.out.println("*");
}
}
}
And please start method names with lowercase and counting with 0. It's common practise and it helps a lot to use the standards right from the beginning.
Like this you can use variable from different methods in different methods
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0;
int a=Sum(sum);
System.out.println("The Average of the numbers is: "+a);
}
public static int Sum(int sum) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total count of number for Average: ");
int a=sc.nextInt();
for(int i=1;i<=a;i++) {
System.out.println("Enter the"+i+"Number: ");
int b=sc.nextInt();
sum+=b;
}
int avg=sum/a;
return avg;
}

Invoking method with array of objects as parameter

Hello I'm having issues running my method bugScan which I think is because I've declared myBugs as an array of objects. If any can give me any hints or point me the right direction of sorting this out I would very much appreciate it :) Below is all the appropriate classes:
package mainFuncs;
import java.util.Scanner;
public class aBug {
String species, name;
int x, y, energy, id, foodpref;
char symbol;
public void bugScan(aBug[] bugObjects, Scanner scan) {
String inSpecies, inName;
int inX, inY, inEnergy, inId;
for(int i = 0; i < bugObjects.length; i++)
{
System.out.print("Species: ");
inSpecies = scan.nextLine();
System.out.print("Name: ");
inName = scan.nextLine();
System.out.print("X position: ");
inX = scan.nextInt();
System.out.print("Y position: ");
inY = scan.nextInt();
System.out.print("Energy: ");
inEnergy = scan.nextInt();
System.out.print("ID: ");
inId = scan.nextInt();
bugObjects[i].symbol = '*';
bugObjects[i].species = inSpecies;
bugObjects[i].name = inName;
bugObjects[i].x = inX;
bugObjects[i].y = inY;
bugObjects[i].energy = inEnergy;
bugObjects[i].id = inId;
}
}
}
This is the other class:
package mainFuncs;
import java.util.Scanner;
public class mainMenu {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
aBug[] myBugs = new aBug[5];
myBugs.bugScan(myBugs, scan);
System.out.print("hi");
}
}
My issue is occurs at the line:
myBugs.bugScan(myBugs, scan);
with the error message "Cannot invoke bugScan(aBug[], Scanner) on the array type aBug[]"
You defined the method in the aBug class, but you trying to call it on an array of aBug objects! Anyway, I think you can take the bugScam method out from the first class and place it inside the second class.
package mainFuncs;
import java.util.Scanner;
public class aBug {
String species, name;
int x, y, energy, id, foodpref;
char symbol;
}
Second class:
package mainFuncs;
import java.util.Scanner;
public class mainMenu {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
aBug[] myBugs = new aBug[5];
bugScan(myBugs, scan);
System.out.print("hi");
}
public static void bugScan(aBug[] bugObjects, Scanner scan) {
String inSpecies, inName;
int inX, inY, inEnergy, inId;
for(int i = 0; i < bugObjects.length; i++)
{
System.out.print("Species: ");
inSpecies = scan.nextLine();
System.out.print("Name: ");
inName = scan.nextLine();
System.out.print("X position: ");
inX = scan.nextInt();
System.out.print("Y position: ");
inY = scan.nextInt();
System.out.print("Energy: ");
inEnergy = scan.nextInt();
System.out.print("ID: ");
inId = scan.nextInt();
bugObjects[i].symbol = '*';
bugObjects[i].species = inSpecies;
bugObjects[i].name = inName;
bugObjects[i].x = inX;
bugObjects[i].y = inY;
bugObjects[i].energy = inEnergy;
bugObjects[i].id = inId;
}
}
}
The typ parameter aBug will not be acceptable. By own written classes, the name should be written in camel case, so that could be the case of the exception.
the problem is with the line you mentioned!!
myBugs is an array and does not have any method bugScan
it should be something like this
new aScan().bugScan(myBugs, scan);
myBugs is an array, so you will only be able to perform array operations on it. Your method bugScan() is defined inside the aBug class. If you want to run it you can solve it by doing:
Bug tmp = new aBug();
tmp.bugScan(myBugs, scan);
But this smells like bad coding, the aBug class shouldn't have the responsibility the 'scan for bugs'.
On a side note: By convetion class names start with a capital and even if you apply the fix it will throw a NullPointerException because you never initialize your array.

Categories