Could anyone please explain to me why the add() method returns 0 instead 4?
I am trying to use int 0 in case "invalid" string number is provided (e.g. four).
I am getting the right results for String arguments 3,4 / 3,four / three,four / but not for three, 4.
Can you please give me hints what I am doing wrong?
Thanks!
public class Numbers2
{
public static void main(String[] args) {
System.out.println(add("d","4"));
} // main() method
public static int add(String a, String b)
{
int x = 0;
int y = 0;
try{
x = Integer.parseInt(a);
y = Integer.parseInt(b);
System.out.println("No exception: " + (x+y));
return x + y;
}
catch (NumberFormatException e){
if(x != (int) x ){
x = 0;
}
if(y != (int) x ){
y = 0;
}
return x + y;
}
} // add() method
} // class
Because the second argument is "d", you will always fall to the exception case. Here, x = y = 0.
Your If statements here will no do anything, as (x == (int)x) always when x is an int and (y == (int)x) as they are both 0 so neither of these blocks get executed.
Thus, x + y will always = 0.
The problem is that the line y = Integer.parseInt(b); doesn't get the chance to execute as you are passing "d" as the first argument which is not an integer, the line x = Integer.parseInt(a); results in exception and both x and y remain 0.
You could solve the problem by using separate try/catch for both:
int x = 0; //x is 0 by default
int y = 0; //y is 0 by default
try {
x = Integer.parseInt(a); //x will remain 0 in case of exception
}
catch (NumberFormatException e) {
e.printStackTrace();
}
try {
y = Integer.parseInt(b); //y will remain 0 in case of exception
}
catch(NumberFormatException e) {
e.printStackTrace();
}
return x + y; //return the sum
If you use wrong formate argument as first argument then exception occurs at statement
x = Integer.parseInt(a);
The line
y = Integer.parseInt(a);
is never executed in this case, so use different try-catch block for each statement.
Related
I am trying to get all the neighbors of a combination of simple one character strings in a 2d array. Meaning, my output looks like this currently in a 3x5:
A B C
D E F
A S D
F S A
G S A
So the neighbor of (1,0) should be = A B E S A .
Currently I have the following:
public void getNeighborsOfPoint(int x, int y) {
for (int xx = -1; xx <= 1; xx++) {
for (int yy = -1; yy <= 1; yy++) {
if (xx == 0 && yy == 0) {
continue; // You are not neighbor to yourself
}
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
if (isOnMap(x + xx, y + yy)) {
System.out.println(grid[x+xx][y+yy]);
}
}
}
public boolean isOnMap(int x, int y) {
return x >= 0 && y >= 0 && x < length && y < width;
}
However it is only returning A E A in the example I provided.(it is not returning the ones cross-wise)
What is the right code to make it work? Note that the input will not always be 3 x 5. It may be a lot of different combination of x and y s.
The diagonals aren't included because of this code:
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
When it's on the diagonal Math.abs(xx) == 1 && Math.abs(yy) == 1. So their sum will be greater than 1. You're skipping over the diagonals by having this code here.
The reason you're not getting the diagonals in your current group is that second if statement. You need to cover, for example, (2, 1) which is when xx is 1 and yy is 1. But abs(1) + abs(1) = 2 and 2 > 1, so you don't include it.
As a refactoring exercise, it might be a little cleaner if you have the inside of that for loop simplified to one conditional.
if (expression) {
continue
};
// other stuff
is equivalent to
if (!expression) {
// other stuff.
}
And for you, expression (in psuedocode) is not(xx=0 and yy=0) and isOnMap(xx, yy)
In a loop, the continue keyword means that you will skip to the next iteration of the loop. In your case, you have :
if (Math.abs(xx) + Math.abs(yy) > 1) {
continue;
}
if (isOnMap(x + xx, y + yy)) {
System.out.println(grid[x+xx][y+yy]);
}
So if the first condition is verified, you will not print any answer, meaning that your program won't consider A(xx, yy) to be a neighbord.
In your ABESA example, B and S are ignored because of this.
If you want to use 2d arrays with variable number of rows and columns you have to pass them as parameters in your's isOnMap method like below:
public static boolean isOnMap(int x, int y, int length, int width) {
return x >= 0 && y >= 0 && x < length && y < width;
}
You can handle the special cases of your 2d array (when one or both rownumber and columnnumber of your element are equal to 0) rewriting your getNeighborsOfPoint method in this way:
public static void getNeighborsOfPoint(int x, int y, char[][] grid) {
final int length = grid.length;
final int width = grid[0].length;
if (isOnMap(x, y, length, width)) {
for (int i = Math.max(0, x - 1); i < Math.min(length, x + 2); ++i) {
for (int j = Math.max(0, y - 1); j < Math.min(width, y + 2); ++j) {
if (i != x || j != y) {
System.out.println(grid[i][j]);
}
}
}
}
}
I had to write a code to calculate the remainder using a certain way. I know that there are better ways to do it but that's how I have to proceed.
The if (rem(x - 1, y) + 1 == y) is making extra calls. As it enters there every time before getting to the last return, but it is an important step for my algorithm. I was wondering if there was any way to avoid it.
Also, I know that I have to check if y == 0; I am just trying to improve the performance for now.
Thanks
int rem(int x, int y)
{
if (x == 0)
{
return 0;
}
if (rem(x - 1, y) + 1 == y)
{
return 0;
}
return rem((x - 1), y) + 1;
}
I get 9 recursive calls for rem(3/2)
Sure, this is how you can make it much better.
int rem(int x, int y) {
if (x == 0) {
return 0;
}
int ret = rem(x - 1, y);
if (ret + 1 == y) {
return 0;
}
return ret + 1;
}
We can just call the function once and store its output in a variable.
Yeah sure, In java you do this in following way:
public static void main(String args[]) {
int remainder = remainder(3,2);
System.out.println(remainder);
}
static int remainder(int n1, int n2) {
int x;
x = n1;
if (x >= n2) {
x = x - n2;
remainder(x, n2);
}
return x;
}
Note: I've not added condition to check 0 in the code.
Hope this helps.
I have written this function for finding the number of Square Roots between two numbers (inclusive).
static int FindRoot(int no1, int no2) {
int res = 0;
for (int x = no1; x <= no2; x++) {
for (int y = 1; y <= no2; y++) {
if (y * y == x)
res++;
}
}
return res;
}
This will work fine, but I was thinking about it's performance.
Because in this case the inner For loop will execute from starting position(1), so it'll take time if someone passes a large number range to the method.
So, my question is:
Is there any other way i can find this with better performance?
P.S.- I can't use Math.sqrt() function
static int FindRoot(int no1, int no2) {
int res = 0;
int x = 0;
// Ignore squares less than no1
while(x*x < no1) {
x++;
}
// Count squares up to and including no2
while(x*x <= no2) {
res++;
x++;
}
return res;
}
You can get away with having a single for loop by getting rid of the outer loop
static int findRoot(int lo, int hi) {
int numRoots = 0;
for (int x = 0, x2 = 0; x2 <= hi; x++, x2 = x * x) {
if (x2 >= lo) {
numRoots++;
}
}
return numRoots;
}
here you effectively just do your inner loop once, incrementing numRoots when x2 (x-squared) is between lo and hi, and terminating the loop when x2 is greater than hi (instead of when x is greater than hi like in your code).
It'll work as well.
static int FindRoot2(int no1, int no2) {
int res = 0;
int inner=1;
for (int x = no1; x <= no2; x++) {
for (int y = inner; y <= no2; y++) {
if (y * y == x)
{
inner=y;
res++;
}
}
}
return res;
}
In this case inner loop will not start executing from 1.
There are many reasons why your current algorithm is ineffecient, but the biggest one is that the inner for loop is not necessary.
The idea behind the algorithm you're looking for, is to start at the lowest perfect square higher than or equal to no1, then go to the next perfect square and the next and the next, keeping track of how many you hit, until the perfect square you're on is higher than no2.
static int FindRoot(int no1, int no2) {
int res = 0;
int x = 1;
// This loop gets x to the first perfect square greater than
// or equal to no1
while( (x * x) < no1 ) {
x++;
}
// This loop adds 1 to res and increases x
// as long as x^2 is less than or equal to no2
for(; (x * x) <= no2; x++, res++) { }
return res;
}
Well, all i need to do is this:-
and i got the logic sorted as well(i think i have)
suppose x = 1.
e are the number of events that occur. if e is 0, then just return 1.
else if, e is 1 or any odd number return x * 2.
else if, e is 2 or any even number return x*2(the value of event e2 -1) + 1.
and so on.
here is my function
public int answer(int f) {
int x = 1;
int y = 0;
if (f == 0) {
y = x;
} else if (f == 1) {
y = x * 2;
} else if (f == 2) {
y = (x * 2) + 1;
} else if (f % 2 == 0) {
y = answer(f - 1) + 1;
} else if (f % 2 != 0) {
y = answer(f - 1) * 2;
}
return y;
}
now, the catch is, I can have an arraylist to decide the number of events and have to print out the value of y for all events. the example input would be like:
2 //number of events, this is the number of elements that would be in the arraylist.
2 // this event runs for 2 cycles. so the output would be (x * 2) + 1
3 // this event runs for 3 cycles. so the output would be ((x * 2) + 1)*2 (eventcycles-1*2)
the error message -
Exception in thread "main" 3
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Solution.main(Solution.java:21)
here is my main method to make things clearer:
public static void main(String[] args) {
int x = 1;
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
Solution soln = new Solution();
ArrayList<Integer> casearray = new ArrayList<Integer>();
ArrayList<Integer> ansarray = new ArrayList<Integer>();
for (int i = 0; i < cases; i++) {
int acase = input.nextInt();
casearray.add(acase);
}
for (int elem : casearray) {
int f = casearray.get(elem); ***//this is the error line***
int z = soln.answer(f);
System.out.println(z);
}
input.close();
}
The question is - why am i getting the indexoutofboundsexception? What is really wrong with my code?
It would be highly appreciated if the answer revolves around my logic, if it is correct that is.
for (int elem : casearray) {
int f = casearray.get(elem); ***//this is the error line***
int z = soln.answer(f);
System.out.println(z);
}
Your for loop is iterating through each value in your casearray, not through the indexes. So when you do casearray.get(elem) you're trying to use the value as the index, and it is out of bounds.
Perhaps you meant this:
for (int elem : casearray) {
int z = soln.answer(elem);
System.out.println(z);
}
for (int elem : casearray) {
int f = casearray.get(elem);
...}
the elem is the element in the array, it is not the index. but get(int index) expects the index. The element value could greater than the max index of your arrayList. That's why you got that error.
You just need to do:
for (int elem : casearray) {
int z = soln.answer(elem);
//print...
...}
I'm not sure how to exactly use the the public static method with if/else statements that only return a character. The program is supposed to take x,y and return what quadrant the coordinates are located within. (A noob to java!)
import javax.swing.JOptionPane;
public class Assignment13 {
public static void main(String[] args) {
String userInputx,
userInputy;
double x, y, answer;
userInputx = JOptionPane.showInputDialog("Please enter your x coordinate.");
x = Double.parseDouble(userInputx);
userInputy = JOptionPane.showInputDialog("Please enter your y coordinate.");
y = Double.parseDouble(userInputy);
answer = MethodQuad.quadrant(x, y);
System.out.println("The coordinates " + x + y + "are located Quadrant " + answer);
}
}
class MethodQuad {
public static double quadrant(double x, double y) {
if (x > 0 && y > 0) {
return System.out.println("1");
} else if (x < 0 && y > 0) {
return System.out.println("2");
} else if (x < 0 && y < 0) {
return System.out.println("3");
} else if (x < 0 && y > 0) {
return System.out.println("4");
} else {
return System.out.println("0");
}
}
}
It work like in another programming language. If you wrote return value, you must return some value)
class MethodQuad {
public static int quadrant(double x, double y)
{
if(x > 0 && y > 0)
return 1;
else if(x < 0 && y > 0)
return 2;
else if(x < 0 && y < 0)
return 3;
else if (x<0 && y >0)
return 4;
else
return 0;
}
}
You're telling the method that it will return a double in its signature line:
public static double quadrant(double x, double y)
The compiler won't like this since the method is not in fact returning a double (nor should it). I suggest you change that line so that it knows it will return a String instead. You probably know how to do this, right?
Also, in your class, you're declaring answer to be a double variable which doesn't make logical sense:
double x,
y,
answer;
What variable type should answer be declared as?
Edit
You'll also want to post your assignment instructions so we can see exactly what you're supposed to be doing. You could potentially make answer an int and have the method return an int -- if that's what the teacher wanted. So let's see what they told you to do.