Exchange values between classes/Methods - java

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);
}
}
}
}

Related

Calling a boolean method from a class

i just made a problem which should return if a number "isHappy" or not. A number is happy if it meets some criteria:
A happy number is a number defined by the following process:
-Starting with any positive integer, replace the number by the sum of the squares of its digits.
-Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
-Those numbers for which this process ends in 1 are happy.
`
import java.util.HashSet;
import java.util.Set;
class Solution{
public int getNext(int n){
int totalSum = 0;
while(n > 0){
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n){
Set<Integer> seen = new HashSet<>();
while( n!=1 && !seen.contains(n)){
seen.add(n);
n = getNext(n);
}
return n==1;
}
}
class Main {
public static void main(String[] args){
isHappy(23); //this doesnt work.
}
}
`
I don't know how to call this function, tried different methods like int number = 23 for ex and then isHappy(number) sout(isHappy(number)); , number.isHappy() although this makes no sense, intellij is telling me to make a method inside main but i dont think i must do this, think there s another way.
There are a couple of problems here. When you run a Java application it looks for the main method in the class you run. Your class has no main method, instead it has an inner class that has a main method.
class Solution {
// existing methods
// no 'Main' class wrapping method
public static void main(String[] argv) {
}
}
The second problem is that main is a 'static' method but isHappy is an 'instance' method. To call it you need an instance of the class
// inside the `main` function
var sol = new Solution();
if (sol.isHappy(23)) {
System.out.println("23 is happy");
} else {
System.out.println("23 is not happy");
}
You have completely solved the problem. You only have to decide what to do with the result of your calculations. You can simply print a string depending on the result.
Please note, that the methods in your Solution class are not static. So, you need to create an instance of the class and call the methods on that instance.
import java.util.HashSet;
import java.util.Set;
class Solution {
public int sumOfDigitsSquares(int n) {
int totalSum = 0;
while (n > 0) {
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfDigitsSquares(n);
}
return n == 1;
}
}
class Main {
public static void main(String[] args) {
var solution = new Solution();
String answer = solution.isHappy(23) ? "Is happy" : "Not happy at all";
System.out.println(answer);
}
}
Here is one possible way to check all numbers from 1 to 100 for happiness and print the result for each number.
IntStream.rangeClosed(1, 100)
.mapToObj(i -> "" + i + " " + (solution.isHappy(i) ? "is happy" : "not happy"))
.forEach(System.out::println);
To call non-static methods of a class, you need an instance:
public static void main (String [] args) {
Solution foo = new Solution ();
boolean bar = foo.isHappy (49);
// do something with bar
}
To use a static method, you don't use an instance:
class Solution{
public static int getNext(int n){ ... etc ...
}
public static boolean isHappy(int n){ ... etc ...
}
public static void main (String [] args) {
boolean foo = isHappy (1024);
// do something with foo
}
Another problem is you are throwing away the result of isHappy (23).
System.out.println (isHappy(23));
System.out.println ("is 23 happy?" + (isHappy(23) ? "Yes" : "No");
are two possibilities.

Trying to print a subclass method in a main class in java

I have three classes. An abstract class, a derived class and a main class. I am trying to print the method in the derived class in the main class.
public abstract class newsPaperSub {
public String name;
public abstract void address();
public double rate;
}
Derived class:
import java.util.Scanner;
public class PhysicalNewspaperSubscription extends newsPaperSub {
#Override
public void address () {
String subAddress = " ";
Scanner input = new Scanner(System.in);
int i;
int digitCount = 0;
for (i = 0; i < subAddress.length(); i++) {
char c = subAddress.charAt(i);
if (Character.isDigit(c)) {
digitCount++;
System.out.println("Pease enter an address: ");
subAddress = input.nextLine();
if (digitCount <= 1) {
rate = 15;
System.out.println("Your subscrption price is: " + rate);
}
}
}
}
}
Main class: I havent been able to figure out what to exactly put in the main class in order to print the function in the derived class. I have tried a couple things with no luck. Any help would be greatly appreciated.
public class demo {
public static void main (String [] args) {
}
}
Just put inside of the main method
PhysicalNewspaperSubscription subscription= new PhysicalNewspaperSubscription()
and then call your method
subscription.address()
in the main method as well.
Simply put:
public class demo {
public static void main (String [] args) {
PhysicalNewspaperSubscription pns = new PhysicalNewspaperSubscription();
pns.address();
}
}
... but your code will not do anything.
The reason being because though you have a Scanner to read in something from the console, it'll never run that piece of code because the following loop structure never runs:
for (i = 0; i < subAddress.length(); i++) {
...
}
The reason it does not run is because when you declare subAddress you set it to an empty String (String subAddress = " ";), so when the loop checks the condition (i < subAddress.length()) it'll evaluate FALSE, because 0 < 0 is FALSE and hence not run the loop.

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.

Printing contents of an array in a non-sequential order using threads

Having trouble printing the contents of my array in a non synchronized way. I am looking to iterate through and output the letters "A" , "B" , "C" in a non sequential manner from a static array of strings using Threads to print the loop.
Here is my code:
public class ThreadWithExtends extends Thread {
public ThreadWithExtends() {
super();
}
public void run() {
String[] arr = { "A", "B", "C" };
int num = 10;
try {
for (int j = 0; j < num; j++) {
for (int i = 0; i < arr.length; i++) {
sleep((int) (Math.random() * 1000));
System.out.print(arr[i] + " ");
}
}
} catch (InterruptedException e) {
System.out.println("Finished");
}
}
}
My TestThread class:
public class TestThread {
public static void main(String args[]) {
new ThreadWithExtends().start();
}
}
My Output : A B C A B C A B C A B C A B C A B C A B C A B C A B C A B C
My Desired Output : C A B A B C B A C .. etc , not sequential like above.
Actually you aren't executing any code in parallel. You only created one thread that prints some statements sequentially. You need to create three threads that print stuff on their own, like so:
public class Printer extends Thread {
private String mText;
public Printer(String text) {
mText = text;
}
#Override
public void run() {
int num = 1_000;
for (int i = 0; i < num; i++) {
System.out.print(mText + " ");
}
}
}
and then
public static void main(String args[]) {
new Printer("A").start();
new Printer("B").start();
new Printer("C").start();
}
Now you have three threads that run in parallel. Prints should be mixed now.
Note that in general you shouldn't care about how the scheduler schedules the threads. It tries to optimize and it works well. It probably has its reasons why it scheduled this or that way. You can assign priorities to threads if you want to tell the scheduler your preferences.

Break from called method in java

I have two methods:
public void test() {
for (int i = 0; i <= 10; i++) {
a();
}
}
public void a() {
// ...
}
Suppose the test method is fixed, I can not modify it.
How can I break the for loop in the a method?
You can throw an unchecked exception.
Another solution is to sub-class the class which has the first method and fix it so it can stop early e.g. if a() return true.
You can throw an exception, or you could simply use break;. This is a little less work, as you don't need to handle an exception at all.
Example:
public class Test
{
public static void main(String[] args)
{
foo();
}
public static void foo()
{
int i = 0;
for(i = 0; i <= 10; i++)
{
System.out.println("in loop: " + i);
if(i == 5) break;
}
System.out.println("end value: " + i);
System.out.flush();
}
}
The end value of i will be 5.

Categories

Resources