Can someone explain the "static" requirement for my code? - java

I am working through hackerrank and I felt pretty solid about my code, but it doesn't work. Evidently, it has something to do with the way that I named the variables. Ultimately, the goal was to output the area of a rectangle if the area is positive, and if not,
System.out.println("java.lang.Exception: Breadth and height must be positive")
This was my code:
int B = scan.nextInt();
int H = scan.nextInt();
scan.close();
Boolean correct = (B > 0) || (H > 0);
if(correct){
int area=B*H;
System.out.print(area);
}
else correct = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
scan.close();
This is the code that actually works:
private static int B;
private static int H;
private static boolean flag;
static {
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
H = scan.nextInt();
scan.close();
if (B <= 0 || H <= 0) {
System.out.println("java.lang.Exception: Breadth and height must be positive");
flag = false;
} else {
flag = true;}
I expected the input of negative integers to output the Breadth and height error, but instead it outputs
20java.lang.Exception: Breadth and height must be positive
Rather than using someone else's code (the second example), I would really like to fix my own code idea and understand the use of the static class better.

First, your condition should contain and AND not an OR. The input is correct if both the height and the width are positive.
Second, you have missed out braces after the else, so the println happens in all cases.
Also:
You don't need to use Boolean, you can use boolean.
You don't need to set correct to false after the else. In fact, you don't need it at all.
Your indentation is wrong. It is much harder to get your code right if it is not indented correctly.
Java variables should be lower case (b and h, not B and H).
Practice spending a bit more time reviewing your own code and learning how to debug it because these are very basic errors. It will help you a lot.

Your condition sould use && insteed of ||. Ans since you dont put {} to the else it only affect the correct = false; and not the print.err
int B = scan.nextInt();
int H = scan.nextInt();
scan.close();
Boolean correct = (B > 0) && (H > 0);
if(correct){
int area=B*H;
System.out.println(area);
} else
System.err.println("java.lang.Exception: Breadth and height must be positive");
scan.close();

You have several problems in your code:
(B > 0) || (H > 0) This condition should use AND instead of OR: (B > 0) && (H > 0)
You forgot curly brackets at your "else" part of code.
Do not "throw exceptions" that way. It's hmm... weird.
This is what you want to do:
if (correct) {
int area=B*H;
System.out.print(area);
} else {
correct = false; //as long as your're throwing exception in this block, this assignment is redundant
scan.close();
throw new Exception("Breadth and height must be positive");
}
P.S. Also to mention. You probably do not want to use a static block to put your code into. Use methods instead. Something like: public int getSquare() { } and place your code inside.

Related

How do I break out of this recursive call?

I am a newbie to recursion and I am still learning it, so please tolerate my poor logic if it is bad. I have this function which has 5 parameters a,b,c,x,y. so what I essentially want to do is take an element out of either of these variables and add it to the other to finally get x , y. I want to try out this by myself and I have nearly done it, only i wanted to ask if there's any way i could get out of this recursive call, once I get the answer as "YES".
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
int[] input = new int[10];
for(int i=0; i < 10; i=i+2) {
input[i] = Integer.parseInt(String.valueOf(in.charAt(i)));
}
int A = input[0];
int B = input[2];
int C = input[4];
int X = input[6];
int Y = input[8];
persistent(A,B,C,X,Y);
}
private static void persistent(int a, int b, int c, int x, int y) {
if(a == 0 || b == 0 || c == 0) {
if((a == x && b == y) && (b == x && a == y)) {
System.out.println("YES");
}
else if((b == x && c == y) || (c == x && b == y)) {
System.out.println("YES");
}
else if((a == x && c == y) && (c == x && a == y)) {
System.out.println("YES");
}
else {
return;
}
}
persistent(a-1,b+1,c,x,y);
persistent(a-1,b,c+1,x,y);
persistent(a+1,b-1,c,x,y);
persistent(a,b-1,c+1,x,y);
persistent(a+1,b,c-1,x,y);
persistent(a,b+1,c-1,x,y);
}
Your code never does.
Recursive algorithms pretty much all boil down to this exact same style:
First, check if some edge case has been reached (generally, the very simplest case). In this case, return immediately - do not recurse. By tautology, if the answer is so easy you can just give it without needing to recurse, that defines 'edge case' / 'simple case'. There must be at least one such case, or a recursive algorithm cannot work.
Otherwise, provide your answer and feel free to employ as many recursive calls as you prefer, but every single last one of those calls must be simpler, defined by the idea that it is strictly closer to that simple case as mentioned in 1.
All state is conveyed via parameters. It is common to have a private helper method that does the actual work which has a bunch of extra parameters, and the public API that is a one-liner that calls the helper, providing initial values for those extra parameters. Only if you have no such state can you omit this one.
Your code isn't doing this. There is a simple case, which is if a or b or c is 0, but your 6 recursive calls are not clearly moving towards simplicity.
The fix is not obvious. Your algorithm cannot work as written and cannot be fixed without considerably rethinking it.
Hopefully the above will help you: Your recursive calls need to become simpler somehow, guaranteed. Right now it's not guaranteed: Yes, every call is moving one of the 3 numbers closer to the edge case (be 0), but there is no clear flow: If I call your code with, say, 3/4/5 as arguments, then it makes recurisve calls with 2/5/5, 2/4/6, etcetera. That first call (2/5/5) is not moving guaranteed closer to the edge case, because as part of its call stack, it'll be doing 3/4/5 again.

from recursion to if else statments

how do I transform this into a if else statement? im stuck in one part with the comment below. I would like to separate knapsack() into if statements.
static int max_val(int a, int b){
return(a>b)? a: b; //set value for a = 1 and b = 0
}
static int knapsack(int max_bag_limit, int[] weight, int[] value, int size){
if (size ==0 || max_bag_limit == 0){ //base case
return 0;
}
if(weight[size - 1] > max_bag_limit){
return knapsack(max_bag_limit, weight, value, size-1);
}
else{
return max_val(value[size-1]
+ knapsack(max_bag_limit - weight[size - 1],weight,value, size -1), //im stuck at this line
knapsack(max_bag_limit, weight, value, size -1) );
}
}
i tried to do it this way because i need to put it in a Jbutton.
else if(counter == 6){ //max_val compare knapsack A and Knapsack B
printCode(1);
if(knapsackA>knapsackB){
total = knapsackA;
}
else total = knapsackB;
}
else count = 1; // to avoid 0;
}
To allow more control over the algorithm, you need to break out one step to perform. This means that you need to think about what to do for a single step and what state you need to store so that you can perform the next step. A direct reimplementation of recursion can use an explicit Stack instead of relying on the call stack in the JRE.

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

Passing variables through if statements without new method

So well I'm just here wondering if there's a way to pass a variable through a statement. Something like this:
if (a < b) {
double g = 1
} else if (a > b) {
double g = 0
}
if (g = 1) {
System.out.print("true");
} else {
System.out.print("false");
}
Mainly saying, I want to set a variable if a statement is true or not, go to the next section of code and print out "true" or "false" and I pretty much am just wondering if this is possible without creating a new method (and of course if there is code for it).
Thank you.
You are almost there. You have to declare g outside the if statements, so you can access to it whithin the whole function. Read more about scopes, if you declare a variable inside a block {}, it will be accessible just inside it, so when you declared it into the if-else if blocks, you couldn't access to the variable outside.
Also to compare a primitive type (in this case double) you have to use == operator, because = is used for assignment.
double g;
if (a<b) {
g = 1;
}
else if (a>b) {
g = 0;
}
// What happen if 'a = b'?
if (g == 1) {
System.out.print("true");
}
else {
System.out.print("false");
}
Note: What value will take g if a == b? You may want to take care about that case too.
double g;
if (a<b) {
g=1
}
else if (a>b) {
g=0
}
if (g==1) {
System.out.print("true");
}
else {
System.out.print("false");
}
also make sure that you always use == instead of = in your if-statement
The if condition if (g=1) does not work with java. This would work with C though.
You should code if (g==1) to test if g is in fact equal to the int value 1.
You've got three problems.
a and b aren't defined. Define them before entering the if statement.
Define g outside of the if statement (a simple double g; will suffice), then set the values as part of your conditional logic. You do have to give it a default value if you intend to keep the else if there, since Java would complain about that not being defined.
g=1 isn't going to work the way you think it should; you probably mean g == 1.
With else if
int a, b; // assumed instantiated with values
double g = -1; // required since Java can't guarantee that the else-if will be hit
if (a<b) {
g = 1;
} else if (a>b) {
g = 0;
}
With else
int a, b; // assumed instantiated with values
double g; // instantiation not required since Java can guarantee the else case
if (a<b) {
g = 1;
} else {
g = 0;
}
double g; double a = 4.0; double b = 3.0;
if(a < b){
g = 1.0;
System.out.print("true");
}
else if (a > b){
g = 0.0;
System.out.print("false");
}
// Why not write your code like the above example. It seems like the
//same operations are executed but with less lines of code.

How can I tell that an integer is only 2 digits long?

I need to write a Java program that prompts the user to enter an integer consisting of exactly 2 digits; then displays on the screen the sum of its individual digits.
I am stuck here. What am I doing wrong?
import java.util.Scanner ;
public class ss {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x;
System.out.println("Please Enter a number consists of 2 digits only : ");
x = input.nextInt();
x.length() == 2;
}
}
and the last line contains an error!
Assuming that x is positive, a simple way to check if it has exactly two digits would be:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
The variable x is of type int, so you can't call a method on it. You need to either read the input as a String or convert the int to a String then call length(), or just test that the int is between 10 and 99, inclusive.
In a programming langauge, there are things called L-values and R-values. In an assignment operation, a L-value can accept a R-value as input. This comes from the typical layout which has L-values on the left of the assignment operator and R-values on the right side of the assignment operator.
x = 5;
x is the L-value and 5 is the R-value. It is possible to assign five to x.
However, a function returns a R-value. Therefore, it is possible to do this
x = a.length();
but is is not possible to do
a.length() = x;
because you can not assign a value to the return of a function.
Fundamentally, L-values are names which represent a value, but R-values are values or items which when analyzed result in the return of values.
Now, if you used the equals comparison operator, both values must be R-values, because no assignment is being performed
a.length == x
is just fine, because it is not the assignment operator = but rather one of the comparison operators ==.
Your error comes because x is a primitive, not an object. Only objects have methods like length(). A quick an easy way to determine the length of an integer is by using Math.log().
public int length(int n){
if (n == 0) return 1; // because Math.log(0) is undefined
if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
//than wanted. Math.log10(10) == 1.
}
This method uses the fact that the base b logarithm of an integer a is related to the length of the integer a.
Or, if you don't know how to use methods, you could do this (assuming n is the integer to check):
int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);
Or, if you don't use the ternary operator, you could expand it:
int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;
You can't find the length of an int by calling a method on it, but you can find the length of a String.
Try converting the int to a String and finding the length of that:
boolean isTwoDigits = x.toString().length() == 2;
You cannot call length on integer just write
if(x>=10 && x<=99)
{
//write your code here
}

Categories

Resources