Refresher on Java classes in separate files - java

I need a refresher on moving classes from one file into two files. My sample code is in one file called "external_class_file_main". The program runs fine and the code is shown below:
Public class external_class_file_main {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
I move the get_a_random_number class to a separate file called "external_class_file". When I do this, I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method get_a_random_number(int, int) is undefined for the type
external_class_file_main
at external_class_file_main.main(external_class_file_main.java:20)
The "external_class_file_main" now contains:
public class external_class_file_main {
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
The "external_class_file" now contains:
public class external_class_file {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
}

You need to refer t get_a_random_number via the class external_class_file. E.g.:
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
You should definitely stick to Java naming conventions though.

Here the solution:
public class external_class_file_main {
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
But, please, take a look into Java naming conventions.

You no longer have access to the get_a_random_number method from the external_class_file_main class. As the method you need is static you can just refer directly to it as follows:
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
PS you will find it a lot easier to code and for people reading your questions if you use proper Java naming conventions for your methods and classes e.g. no underscores and start classes with a capital letter. http://en.wikipedia.org/wiki/Naming_convention_%28programming%29

Related

Exchange values between classes/Methods

i recently learned the use of public, private and double in my different classes. But for some reason i cant understand why this is not working. My intention was to use three different classes as an exercise: I want Do() to make numbers from 0 to 20 and show only the numbers 0 till 10 on my console using the method for1() in a different class. Can someone please fix this issue? I dont need a shorter code or a code in just 1 class since i need it to educate myself using many classes. I would thank anyone if you could fix this issue using this kind of setup. Thanks in advance.
public class MainM {
public static void main(String[] args) {
loop Q = new loop();
Q.Do();
}
}
//------------------------------------------------------
public class loop {
public double b;
Sum R = new Sum(); // Java shows the problem is here : at Sum.<init>(Sum.java:3)
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1();
}
}
}
}
//--------------------------------------------------
public class Sum {
loop Q = new loop();
public void for1() {
System.out.println("b " + Q.b);
}
}
You can have your Sum class only with the print statement and the method for1() should have one parameter. Bellow is my suggestion
public class Sum {
public void for1(double b) {
System.out.println("b " + b);
}
}
And your loop class will be
public class loop {
public double b;
Sum R = new Sum();
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1(b);
}
}
}
}

Actual and formal parameters

I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.

Java & NetBeans exercise, can't get it to work

I'm a beginner in coding and wanted to train, and so I started doing exercises that I find on the internet, I finished one and was unsatisfied because of how easy it was, and created myself a challenge.
The exercise was: you type in a variable and it tells you if it is above a certain number, in this case it's 50, but here's the thing, I didn't want to type it in, I want it to be randomly generated, but I can't find a way to solve the problem, it blocks at nextInt.
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
random r = new random ();
int Low = 1;
int High = 60;
int mark = r.nextInt(High-Low)+ Low;
System.out.println("The mark is " + mark);
if (mark>50) {
System.out.println("PASS");
} else {
System.out.println("Fail");
}
}
private static class random {
public random() {
}
}
}
Use Java's Random class instead of defining your own private static class.
import java.util.Random;
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
Random r = new Random ();
int Low = 1;
int High = 60;
int mark = r.nextInt(High-Low)+ Low;
System.out.println("The mark is " + mark);
if (mark>50) {
System.out.println("PASS");
} else {
System.out.println("Fail");
}
}
}

Illegal start of expression, not sure why

I'm a first year programmer and not completely certain on what I'm doing wrong with this code. Please, can anyone help?
package ________;
public class _______
{
public static void main(String[] args)
{
public int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
}
This line displays an illegal start of expression method every time I attempt to compile or run the program:
public int getFactorial(int number)
The ____'s just represent the hidden package and class names. Using NetBeans IDE 7.4, Java apllication
You cannot have other methods or functions inside the main function. You can however call the functions from your main function.
Please write the code as
public static void main(String[] args)
{
int number = 10;
/* if you want user to input */
Scanner get = new Scanner(System.in);
number = get.nextInt(); // get the next integer user types :)
getFactorial(number);
}
public static int getFactorial(int number)
{
int factor = 1;
if (number == 1)
{
System.out.println("Returned 1");
}
else
{
factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
}
return factor;
}
This way, your function would be inside the same Class but outside the bounds of Main method. In the main method, you would be calling it and where the control would be transfering to the getFactorial function.
You have a method (getFactorial) inside another (main). They need to come one after another.
public static void main(String[] args){
getFactorial(int number);
}
public static int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
You can't write a method inside another method. Your code should look like this:
package ________;
public class _______ {
public static void main(String[] args) {
//call getFactorial, for example
int result = getFactorial(2);
}
public static int getFactorial(int number) {
if (number == 1) {
System.out.println("Returned 1");
return 1;
} else {
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}

Write a program to accept number from command line and display sum of digits in a number by using recursive funcion

I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)

Categories

Resources