How to use Final Variables belonging to one block in another? - java

final int a, b;
if (condition1) {
a = get(dynamicValues);
b = get(dynamicValues);
}
if (condition2) {
int c = b + a;
display(c);
}
In this type of code the compiler is asking to intialize a and b, which I can't do until the condition1 is met. and a and b being final is mandatory as the values of hours and minutes keep changing.
The above written code is very generalized just to give you an idea of my problem.
UPDATE: The problem here is condition2 is one of the else conditions of condition1. So can't use else statements too.
Dynamic values here are the values like "hrs and mins" which always change. when condition1 is met a and b are intialised with hrs and mins, condition2 will definitely happen after condition1 at some point of time. So the time difference between condition2 and condition1 needs to be calculated.

if condition1 is false a and b remain not initialized. That's why the compiler is complaining. Add the else branch and it will compile correctly
if(condition1)
{
a=cal.get(Calendar.HOUR);
b=cal.get(Calendar.MINUTE);
} else {
a = 0;
b = 0;
}

Forgive me if I have not understood your problem correctly :). It seems to me that perhaps it's easier to wrap up your 'final' variables into an immutable class. Then create an instance of such a class in 'condition1'. Here's what I mean...
import java.util.Scanner;
import java.util.Calendar;
public class ImmutableHourMinute {
private final int a;
private final int b;
public ImmutableHourMinute(final int $a, final int $b){
this.a = $a;
this.b = $b;
}
public int getA() {
return a ;
}
public int getB() {
return b;
}
public static void main(String... args){
// Requirements:
// 1. Hour and minute are set at condition == 1;
// 2. Hour and minutes must never be changed.
System.out.println("Please type 'start':");
Scanner scanner = new Scanner(System.in);
ImmutableHourMinute hourAndMinute = null; // Can be initialized properly later
while(!scanner.nextLine().equals("quit")){
System.out.println("Please enter condition (1 or 2):");
int condition = scanner.nextInt();
if(condition == 1){
Calendar rightNow = Calendar.getInstance();
int a = rightNow.get(Calendar.HOUR);
int b = rightNow.get(Calendar.MINUTE);
System.out.println(String.format("(Creating ImmutableHourMinute(a=%1$d, b=%2$d)", a, b));
hourAndMinute = new ImmutableHourMinute(a, b);
}else if (condition == 2){
display(hourAndMinute.getA() + hourAndMinute.getB());
}
System.out.println("Please enter condition (1 or 2):");
}
}
private static void display(final int displayValue){
System.out.println(String.format("Displaying the time set in condition 1 :%1$d", displayValue));
}
}
And here is a sample of the output:
$ java ImmutableHourMinute
Please type 'start':
start
Please enter condition (1 or 2):
1
(Creating ImmutableHourMinute(a=9, b=56)
Please enter condition (1 or 2):
Please enter condition (1 or 2):
2
Displaying the time set in condition 1 :65
note : such and immutable class already exists(if you're using Java SE 8)...
java.time.LocalDateTime

public class time{
private int a=0;
private int b=0;
public int get()
{
return a+b;
}
public void set()
{
this.a = cal.get(Calendar.HOUR);
this.b = cal.get(Calendar.MINUTE);
}
}
In your main class, call the time class method(out of main method, at very begining),
public final Time t = new Time();
In main method:
if(condition1)
{
t.set();
}
if(condition2)
{
display(t.get());
}

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.

Call function whenever values are changed [duplicate]

This question already has answers here:
How to create change listener for variable?
(5 answers)
Closed 1 year ago.
Can I somehow do that?
public class Test {
public int a = 5;
public int b = 10;
public void change() {
this.a += 1;
this.b += 1;
}
}
Test test1 = new Test();
Test test2 = new Test();
test.valueChanged((a, b) -> {
System.out.println(a + b);
});
test2.valueChanged((a, b) -> {
System.out.println(a - b);
};
test1.change();
// System.out.println: 17
test2.change();
// System.out.println: -5
I'd like to have functions which is called whenever values are changed.
I will have Test created more times and I would like to have different valueChanged as well.
If you wish to be notified when a field changes, then the best way to go is to make that field private and create a setter and getter method for that field. This allows you to put extra code in the setter that will execute when the value will be changed. Example:
public class Test {
private int val;
public void setVal(int val) {
this.val = val;
// Put code here that you want to execute when the value has changed.
}
public int getVal() {
return this.val;
}
}

A method which accepts two integer values as input parameters and returns the boolean

This is one of the practice questions of a test:
Write a method which accepts two integer values as input parameters and returns the boolean result true if the sum of the inputs is greater than or equal to 10 (and falseotherwise)
My answer is below but I don't think it looks correct. Can anyone give me a pointer?
public class Bruh{
public static void main (String [] arg){
int a;
int b;
boolean sum = true;
if ( a+b > 10)
System.out.println ("yo");
else{
sum = false;
}
}
}
You only wrote some code in the main method but you did not create one.
In order to do that you need to actually create a method in your Bruh class like:
public static boolean isSumGreaterThan9(int a, int b){
return (a + b) > 9;
}
Than call it from the main method:
public static void main (String [] arg){
int a = 4; // or whatever
int b = 7; // or whatever
System.out.println(isSumGreaterThan9(a, b));
}
You need to put your logic into a method and change your comparison to >= as per the requirement:
public static boolean isSumGreaterThanOrEqualToTen(int a, int b) {
return (a + b) >= 10;
}

how to differently write this part of the code?

import java.util.*;
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int kvadratek, a, b;
a = sc.nextInt();
b = sc.nextInt();
--a;
--b;
if(a>b) {
kvadratek=b;
b=a;
a=kvadratek;
System.out.println((a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b));
}
else {
System.out.println(a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
}
}
i am new to java coding and i have a question if i can write this part
kvadratek=b;
b=a;
a=kvadratek;
differently so that it will give me the same result as the else part. Is it possible to do it with if, while sentences? I actually don't need the else part of the code if I insert
kvadratek=b;
b=a;
a=kvadratek;
but is there a way to change that part?
First thing, to avoid repeating code, is to extract it to a method:
private static int compute(int a, int b) {
return (a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
Now you want b to be the biggest of the two numbers, and a to be the other one. Instead of swapping them, you could use Math.max and Math.min:
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
System.out.println(compute(Math.min(a, b), Math.max(a, b));
You can use this:
int k = Math.max(a, b)
a = Math.min(a, b);
b = k
After this piece of code, b will be the greater between the original a and b, while a will be the smaller, thus removing the need for the if/else.

Given two numbers, return true if any one of them divides the other, else return false

Given two numbers, return true if any one of them divides the other, else return false
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
boolean aDivisblebyb, bDivisblebya, answer;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bdivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}
I have been getting errors like cannot find symbol
You have a mess of code thrown together and half it it isn't needed. To find if a symbol is not defined, look at the line of code in your IDE where it is complaining and see why that variable is not in scope.
If you only write the code you need, there is less chance of making a mistake, and it is easier to see where the mistake is.
This is how I would write it
public class DividesAB {
public static void main(String[] args) {
int a = 208, b = 7;
System.out.printf("a: %,d divides b: %,d is %s%n", divides(a, b));
}
//write your code here
public static boolean divides(int a, int b){
return a % b == 0 || b % a == 0;
}
}
The variable names are not correct.
aDivisblebyb and you are using aDivisiblebyb
So change the variable names and it should work.
First, look at the "cannot find symbol" error from your compiler. It should tell you exactly what line the error is occurring on, and most likely the exact error that is occurring. In your case, it will point to:
boolean answer = aDivisiblebyb||bDivisiblebya;
In your declaration, the spelling is different (aDivisblebyb vs aDivisiblebyb), so the compiler does not understand what the symbol aDivisiblebyb is. Same goes for aDivisiblebya. Hence the error.
Side note: you have declared boolean aDivisblebyb and boolean bDivisblebya in two places. In the code you posted, it is unnecessary to access these boolean values outside of the divides method (same with the answer boolean). So, to clean it up a little:
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bDivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}

Categories

Resources