Method calling within the same class - java

long time searcher but first time I'm posting a question. I am an IT student going into [haven't started yet] my second programming class. The first was just an intro to Java (we're talking basics really). I have been having a hard time with calling methods within the same class. I have attempted search-foo with poor results. A few articles pop up but they don't cover exactly what I'm looking for. Included is an example (quickly and probably poorly written) to get across what I'm asking. The basic gist [remember to stay with me since I'm new to programming in general] is that I want to add two numbers, creating a third, and have the system display the result...
public class MethodCallExample{
public static void main(String[] args){
int valueTwo = 3;
MethodToCall();
int valueOne;
int TrueValue = valueOne + valueTwo;
System.out.println("The total value is " + TrueValue + "!");
}
public static int MethodToCall(){
int valueOne = 2;
return valueOne;
}
}
When I go to compile I get one of two errors depending on which derp I try to underp. If I compile as its' written, I receive a "valueOne might not have been initialized" error, and if I either move or remove -int valueOne - I receive "cannot find symbol" referring to valueOne. Any help is greatly appreciated since I am still learning.
Sincerely,
Hubert Farnsworth

When you call MethodToCall, you aren't doing anything with the returned value. You need to store the returned value in your variable i.e.
int valueOne = MethodToCall();

It looks like you are confused with the variable scopes. Try doing
int valueOne = MethodToCall();
Inside your main.

When you return something then you need a variable to hold the returned value.. so
int valueone = methodtovalue();
would be correct..
Also note that the variable declared in a function would lose its scope when it is reaches the main program because the variable is declared in function. So valueone in function is different from the valueone declared in main() because valueone in function has its scope only within function and valueone in main has its scope till the end of mainprogram

Related

How can I repeat a method with a variable integer?

I just started learning how to program in Java a month ago. I am trying to make my robot (karel) put a beeper the amount of times that is indicated in the "put" integer only, not the total amount the object has. However, it is not a set number and karel.putBeeper(put); does not get accepted in the compiler due to the class not being applied to given types. Any help would be greatly appreciated, and I am starting to understand why Stack Overflow is a programmer's best friend lol. Note: I might not respond to to any helpful tips until tomorrow.
import java.io.*;
import java.util.*;
public class Lab09 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Which world?");
String filename = input.nextLine();
World.readWorld(filename);
World.setSize(10,10);
World.setSpeed(6);
Robot karel = new Robot(1,1,World.EAST,0);
int pick=0;
int put=0;
for(int i=0; i<8; i++) {
while(karel.onABeeper()) {
karel.pickBeeper();
pick++;
karel.move();
}
for(i=0; pick>i; pick--) {
put++;
}
if(!karel.onABeeper()) {
karel.move();
}
while(karel.onABeeper() && put>0) {
karel.putBeeper(put);
}
}
}
}
If I got your question right, you're trying to putBeeper put times, which is done by the following code:
while (karel.onABeeper() && put > 0) {
karel.putBeeper(put);
}
The issue I see here is that you're not changing the value of put after calls to putBeeper, hence this while loop will never terminate: for instance, if the value of put was 5 during the first loop iteration, it will always remain 5, which is larger than 0. Also, as you've mentioned, putBeeper doesn't take any arguments, hence trying to pass put as an argument won't work - the compiler catches that error for you.
If your intent is to call putBeeper put times then what you can do is decrement put after every invocation of putBeeper - put will eventually reach 0, at which point you've called putBeeper exactly put times. And since you're just learn to program in Java, I'll leave the actual implementation to you as an exercise. Good luck!

How to find out where arguments come from to the specific parameter in Java?

I've come to wonder if there is a way to find out which method arguments are returned from.
If you have a few methods in a few classes, perhaps it's easier to figure out where the values come from to the parameter by looking at the method signature.
What if we have very complicated structure of classes? how can we efficiently figure it out? (other than using debugger)
I would appreciate your advice!
For example,
public class Recursion_fig18_9 {
//recursive declaration of method factorial
public static long factorial(long number){
long result = 1;
//iterative declaration of method factorial
for (long i = number; i >=1; i--){
result *= i;
}
return result;
}
//output factorials for values of 0 to 10
public static void main(String[] args) {
//calculate the factorials from 0 to 10
for (int counter =0; counter <= 10; counter ++){
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
(Although this example is quite small structure of class,)
How can I figure out where "number" is returned from in the factorial method?
Using your debugger you can set a break point within the method. When that method breaks, you'll see a stack frame indicating where the call to the method came from and this will help you to trace back the method call to figure out how it was constructed.
Within your code example, place the breakpoint on the return statement so that you can examine the return value before it is returned.
Alternatively, you could use a logger to generate a log file and see how your code steps through it. You'd be able to back off the logging level after the fact so that you don't have to change code constantly. More on logging here
I am looking back at my old question and I am answering to my own question.
You can figure out easily without using debug which method calls the current method and passes the parameters by
selecting the current method
right mouse click
click Open Call Hierarchy (or Ctrl + Alt + H).

How do I make two classes to work together in Java? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been trying for weeks in this project where I have to make one class that generates 500 random numbers from 1-250 and in a second class I have to inherit the first class properties and write all those numbers in a text file but when I have being having problems getting the properties and work with it and I haven't found a way to do it online.
My First class is
import java.util.Random;
public class GenKeys {
public static void random(){
for (int i = 0; i < 250; i++) {
int x = (int) (Math.random() * 100);
}
}
}
and my second code is
import java.util.Random;
import java.io.*;
import java.lang.*;
public class MainProg extends GenKeys{
public static void main(String[] args){
public static void random(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( x + System.getProperty("line.separator"));// when i compile the x is not found!!!
out.close();
} catch (IOException e) {
System.out.print(e);
}
}
How can I make the two classes work together?
What am i doing Wrong ?
You are using inheritance instead of just using an instance of GenKeys in MainProg
You keep overwriting your random values, since you only use a single variable x, when you should be using e.g. an array
You create 250 values in range [0..99] instead of 500 values in range [1..250]
You don't store or return anything from your random() method
and i havent found a way to do it online.
I'm not sure you've looked hard enough.
How to get your code working
Firstly, you want to change the type and name of your method to an int.
public static int randomNum()
Then, remove the loop from the code, and just return the random number generated:
return (int)Math.Random() * 100; //By the way there is a Random class.
In the random method, you want the loop:
for(int x = 0; x < 250; x++)
{
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( randomNum() + System.getProperty("line.separator"));
}
out.close();
The various issues with your code
You're mis-using inheritance here. Your class is not a type of GenKey. It simply uses it, so it should be a field in your class.
Secondly, a method can only return one value, or one object. It can not return 250 numbers as is. You're assigning 250 numbers to x. This is only going to store the last number generated.
I don't think this is right approach. you need another class, for example KeyWriter to inherit from GenKeys. let it use GenKeys method random (it doesn't need to be static)
also, your random method is wrong, you only generate 250 keys instead of 500, and they are not from 0 to 250.
my solution is:
1) inherit KeyWriter from GenKeys
2) modify random to return only 1 generated number using nextInt
3) use cycle inside KeyWriter to call random 500 times and write those values into a file
4) use KeyWriter class inside you main method
I don't post the actual solution, cause it looks like you're doing your homework.
Well, somethings aren't correct here, but the weirdest of all is that you made the random() function a void.
void random()
Where X goes to? You just create a new int, but do nothing about it.
Besides this, there are other problems, as other folks mentioned around.
I'd recommend you to read about function in Java, especially about the difference between int and void.
Some problems (and comments) I see of the bat:
x is not an instance field and is not stored anywhere thus how can it be accessible from the child class.
Like others have said x is being overwritten with each iteration of your for loop.
Why is the mainProg.random() method declared inside of the mainProg.main() method?
I dont think inheritance is the way to go unless it is absolutely required for this project. Why not just make an instance of your random class inside the main method of the mainProg class?
If you want to use inheritance I believe a call to super.random() will be necessary inside of the mainProg.random() method.(Please someone confirm this. Im not 100% sure)
If it was me I would do something along the lines of this in my GenKeys.random() method:
public int[] random() {
int[] keys = new int[500];
for(int i = 0; i < 500; ++i)
{
keys[i] = (int) (Math.random() * 100);
}
return keys;
}
This code creates and returns an array of 500 keys. NOT in the range of 1-250. See here for that: How do I generate random integers within a specific range in Java?
Hopefully that will get you started on the right track.
x is the local variable of random().
so you can't directly access local variable out side the class.
And you are trying to generate 500 random no. between 1-250 so change the for loop in first class
for (int i = 0; i < 500; i++){
.....
}

Random number generator method for linked list assignment

So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?

"Cannot find symbol" - class with the main method can call methods from one of the other classes but not the second of the others?

I've been lurking here for a little while, but I've come into a problem that I can't solve in some Java programs I'm writing for an assignment. I bet they're not too difficult to figure out, but I'm just not getting it.
I've been getting errors along the lines of this:
RugbyTeamLadderEditor.java:125: cannot find symbol
symbol : method findAveragePoints(java.util.ArrayList<RugbyTeam>)
location: class RugbyTeamLadderEditor
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);
I have three classes, and, from the class with the main method (RugbyTeamLadderEditor), I can call the constructor class, but not the other class which has some methods in it (Part1). Should I be doing something with packages? - all I know is that I didn't learn anything about packages in this introductory programming course that I'm doing, and I'm not sure how they would be received if I were to use them.
My code is a couple of hundred lines long, so I put them in pastebin - I hope I haven't transgressed any faux pas by doing this :/ Every class is in its own .java file.
http://pastebin.com/FrjYhR2f
Cheers!
EDIT: a few fragments of my code:
In RugbyTeamLadderEditor.java:
// if the identification number is equal to 5, then print out the average points of all of the teams in the ArrayList
else if (identificationNumber == 5)
{
double averagePointsToBePrinted = findAveragePoints(rugbyTeams);
}
In Part1.java:
/**
* This method takes a RugbyTeam ArrayList and returns a
* double that represents the average of the points of all
* of the rugby teams
*/
public static double findAveragePoints(ArrayList<RugbyTeam> rugbyTeams)
{
// If there are no objects in the ArrayList rugbyTeams, return 0
if (rugbyTeams.size() == 0)
return 0;
// Declare a variable that represents the addition of the points of each team;
// initialise it to 0
double totalPoints = 0;
// This is a code-cliche for traversing an ArrayList
for (int i = 0; i < rugbyTeams.size(); i++)
{
// Find then number of points a team has and add that number to totalPoints
RugbyTeam r = rugbyTeams.get(i);
totalPoints = totalPoints + r.getPoints();
}
// Declare a variable that represents the average of the points of each teams,
// i.e. the addition of the points of each team divided by the number of teams
// (i.e. the number of elements in the ArrayList); initialise it to 0
double averagePoints = totalPoints / rugbyTeams.size();
return averagePoints;
}
It's not quite finished yet - I still need to put a print statement in to print that double, but it's irrelevant for now because I can't actually get that double to take on a value.
Your are trying to call the method findAveragePoints. With the current implementation you say, that the method will be found in the class RugbyTeamLadderEditor. But the method is defined in the class Part1. So to make this work you prepend the call to the method with Part1. (since it is a static method) and the program should work.
EDIT
The code would basically look like this
double averagePointsToBePrinted = Part1.findAveragePoints(rugbyTeams);
Also every time you try to call a method that is defined in another class than the current you either have to provide an instance of this class or prepend the name of the class (like here Part1) to the method called.
As a side node you should change the name of your variable quitProgram. The name of the variable and its meaning contradict each other. So to make things more clear for anyone reading the code you should change either the name or the handling.

Categories