When I execute this code the output is "140" which is "28*5" but it should be "150" which is "28+31+30+31+30" it should calculate the days between 2 months "feb" and "july"... So it means that the for loop isn't working correctly or what ? and why is that ! can you help me here ??
PS: I tried to change the j++ in the loop to j+1 but Android Studio Says"that's not a statement"
int[] pair = {1,3,5,7,8,10,12};
int[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
for (j = mm; j<month; j++){
if (Arrays.asList(impair).contains(j)){
x = 31 + x;
}else if(Arrays.asList(pair).contains(j)){
x = 30 + x;
}else{
if (year%4==0) {
x= 29 + x;
}else{
x= 28 + x;
}
}
}
System.output.println(x);
}
You are attempting to convert the int[] to a List<Integer> by calling Arrays.asList. But that results in a List<int[]> of a single element (the original int[]), which doesn't contain any value of j. The reason is given in Arrays.asList() not working as it should? -- it's a generic method, and the type parameter must be a reference type. int[] is a reference type (as all arrays are), but int isn't.
That is why the tests all fail and 28 is repeatedly chosen to be added.
Change the declared types of pair and impair from int[] to Integer[], so that Arrays.asList will infer the type as Integer (a reference type) correctly. Then the contains method will work as expected. With this change I get 150.
This is because the asList() requires a class object which is either a collection and Iterable. You could modify your code in the following way:-
Integer[] pair = {1,3,5,7,8,10,12};
Integer[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
for (j = mm; j<month; j++){
if (Arrays.asList(impair).contains(new Integer(j))){
x = 31 + x;
}else if(Arrays.asList(pair).contains(new Integer(j))){
x = 30 + x;
}else{
if (year%4==0) {
x= 29 + x;
}else{
x= 28 + x;
}
}
}
System.output.println(x);
}
This should give you the correct output.
This is because your loop never enters the first two if blocks as that is not how aslist(array).contains(element) works
Java, Simplified check if int array contains int
Checking whether an element exist in an array
Related
I'm trying to create a method in Java that prints the fib series up to the number passed to the method. My issue is that I'm required to use an int return type to return the series and I cannot use recursion.
My First Idea
My original idea was like shown. Which works just fine. It takes an argument of type int and returns void simply printing the numbers as they are calculated.
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
What The Question Asks For
The code below shows what I was tasked to do. It asked for a method that takes an argument of type int and returns type int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
To me this just seems impractical and maybe even impossible to use an int return type. I'm wondering if anyone knows a way this is possible.
Expected Output:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
You can use the equation [(h)^a - (j)^a] * [1/sqrt(5)].
'a' is fibonacci number wanted
'h' is [1 + sqrt(5)] / 2
'j' is [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}
I'm trying to use this array I create in printGrid method throughout my program. Currently, I have to run this method, but the values change because of the math.random method nested in this method and I don't want it to. I just want to run this once and use the output throughout my method, is this possible?
What I've tried - I've tried to return the value of the mapArray (seen in code) and printing that out, I'm having issue with that. I've also tried isolating the math.random method in it's own method to calculate the value of the cookies, but my issue with that is that it only returns one value and I need a dynamic amount depending on the input of the x / y vars. Any suggestions?
public static char[][] printGrid(int x, int y) {
// int [][] mapArray = new int [x][y]; // Gets the information to print the array
mapArray = new char[x][y]; // Gets the information to print the array
double cookies = (x * y) * (.1); // Calculates the number of cookies per x / y input
// Storing '.' in all values of the array
for (int d = 0; d < x; d++) // Moved from below.
{
for (int j = 0; j < y; j++) {
mapArray[d][j] = '.';
}
System.out.println();
}
// Storing '0' in random values of the array and '<' at [0][0]
int c = 0;
for (c = 1; c <= cookies; c++) {
int cookiesPrintColumn = (int)(cookies * Math.random());
int cookiesPrintRow = (int)(cookies * Math.random());
mapArray[cookiesPrintColumn][cookiesPrintRow] = 'O';
mapArray[0][0] = '>';
}
// Copy loop from above to print the grid.
for (int d = 0; d < x; d++) {
for (int j = 0; j < y; j++) {
System.out.print(mapArray[d][j]);
return mapArray;
}
System.out.println();
}
return mapArray;
} // printGrid method close
If you are trying to create an array in a method, and then need to use in throughout your program, such as in main, you aren't going to be able to directly use that exact array because it will be out of scope. You can however create and then initialize the array in main equal to the return statement of your method. For example:
main() {
int[][] example;
example[][] = method(...);
}
int [][] method(...){
int[][] exampleArray = {1,2,3} // your random values here
return exampleArray;
}
Because you are creating the actual array inside of the method, it will not be in scope in main. This however will have the exact values the same, so the random numbers will be identical, and you can continue to use this for the rest of your program.
Use return value:
import package.ClassNane;
class Example {
int x = 1;
int y = 2;
char[][] grid = ClassName.printGrid(x, y);
}
According to this answer https://stackoverflow.com/a/12020435/562222 , assigning an object to another is just copying references, but let's see this code snippet:
public class TestJava {
public static void main(String[] args) throws IOException {
{
Integer x;
Integer y = 223432;
x = y;
x += 23;
System.out.println(x);
System.out.println(y);
}
{
Integer[] x;
Integer[] y = {1,2, 3, 4, 5};
x = y;
x[0] += 10;
printArray(x);
printArray(y);
}
}
public static <T> void printArray(T[] inputArray) {
for(T element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
}
Running it gives:
223455
223432
11 2 3 4 5
11 2 3 4 5
The behavior is consistent. This line:
x += 23;
actually assigns a different Integer object to x; it does not modify the value represented by x before that statement (which was, in fact, identical to object y). Behind the scenes, the compiler is unboxing x and then boxing the result of adding 23, as if the code were written:
x = Integer.valueOf(x.intValue() + 23);
You can see exactly this if you examine the bytecode that is generated when you compile (just run javap -c TestJava after compiling).
What's going on in the second piece is that this line:
x[0] += 10;
also assigns a new object to x[0]. But since x and y refer to the same array, this also changes y[0] to be the new object.
Integer is immutable, so you cannot modify its state once created. When you do this:
Integer x;
Integer y = 223432;
x = y;
x += 23;
The line x += 23 is assigning a new Integer value to x variable.
Arrays, on the other hand, are mutable, so when you change the state of the array e.g. changing one of the elements in the array, the other is affected as well.
When you do this x += 23;, you actually create another object, and you made x point on this new object. Therefore, x and y are 2 different objects.
I'm trying to convert some Octave functions to Java, but I'm not sure I'm this right.
function [y,a] = forwardProp(x, Thetas)
a{1} = x;
L = length(Thetas)+1;
for i = 2:L,
a{i-1} =[1; a{i-1}];
z{i} =Thetas{i-1}*a{i-1};
a{i} =sigmoid(z{i});
end
y = a{L};
end
My Java Function
public class ForwardProp {
public static DoubleMatrix ForwardProp(DoubleMatrix x, DoubleMatrix Thetas)
{
DoubleMatrix a = new DoubleMatrix();
a = DoubleMatrix.concatHorizontally(DoubleMatrix.ones(a.rows, 1), x);
int L = Thetas.length + 1;
DoubleMatrix z = new DoubleMatrix();
for (int i = 2; i <= L; i++)
{
a.put(i - 1, a.get(i - 1));
z.put(i, (Thetas.get(-1) * a.get(i - 1)));
a.put(i, Sigmoid(z.get(i)));
}
return a;
}
}
Can someone tell me if this is right???
As far as I can tell, you are committing a double-fencepost error here:
int L = Thetas.length + 1;
L now equals 1 more than the number of elements in the matrix...
for (int i = 2; i <= L; i++) ...and you are now looping with Thetas.get(i - 1) all the way up to an index that is 2 greater than the highest index available from Thetas.get(int).
Remember, Thetas.get(int) directly accesses the internal array that stores this matrix's data. This can only accept indices from 0 to Thetas.length - 1. So when you call Thetas.get(-1) you will always get an error because -1 is not a valid array index; when you get to the end of the loop and call Thetas.get(i - 1), you will get an error again because there is no element at that location.
You are also initializing your output matrix with DoubleMatrix z = new DoubleMatrix();, which returns a 0x0 empty matrix with no elements. That's not what you want either.
Try to make sure you know which indices your data is in, then rewrite it when you know how to reference the data you are using.
This problem has me puzzled. I tried using a loop like this: Basically I tried to get the first digit from the input and do the formula but it doesn't seem to work. It looks so simple but I can't figure it out. Could you help me? Thanks.
public static int ISBN(String ninedigitNum) {
number = 9;
while (number > 0) {
int nextDigit = ninedigitNum.substring(0,1);
...
}
Checksums (Source: Princeton University). The International Standard
Book Number (ISBN) is a 10 digit code that uniquely specifies a book.
The rightmost digit is a checksum digit which can be uniquely
determined from the other 9 digits from the condition that d1 + 2d2 +
3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith
digit from the right). The checksum digit d1 can be any value from 0
to 10: the ISBN convention is to use the value X to denote 10.
Example: the checksum digit corresponding to 020131452 is 5 since is
the only value of d1 between 0 and and 10 for which d1 + 2*2 + 3*5 +
4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 is a multiple of 11. Create a
Java method ISBN() that takes a 9-digit integer as input, computes the
checksum, and returns the 10-digit ISBN number. Create 3 JUnit test
cases to test your method.
I got it, thanks a lot everyone!
What about it isn't working? Either way, I believe what you're missing is that you're continually getting the same substring, which will be the first number of the string: int nextDigit = ninedigitNum.substring(0,1);. In addition, you're going to want to use an int, not a String; you can technically convert from String to int if desired, but the problem itself calls for an int.
There are two ways to do this that jump to mind. I would do this by realizing that mod in powers of 10 will give you the respective digit of an integer, but the easier way is to convert to a char array and then access directly. Note that there's no error checking here; you'll have to add that yourself. In addition, there are a LOT of 'magic numbers' here: good code typically has very, very few. I would recommend learning more data structures before attempting problems like these; to be honest there's very few things you can do without at least arrays and linked lists.
char[] ISBN = ninedigitNum.toCharArray();
//Process each number
int total = 0;
for(int i=0; i<9; i++){
int current_int = Integer.parseInt(ISBN[i]);
total += current_int * (10 - i)
}
//Find value of d1
for(int i=0; i<9; i++){
if(((total + i) % 11) == 0){
total += i*100000000;
break;
}
}
return total;
In general: Use print outs with System.out.println(x); or use your compiler's debugger to see what's going on during processing.
So,
This is the piece of code that I wrote. I still think it could be made more efficient.
public class Problem3 {
public static String ISBN(String x)
{
char[]temp = x.toCharArray();
int counter = 2;
int sum = 0;
int j=0;
for(int i=8;i>=0;i--)
{
sum+= counter*Integer.parseInt(""+temp[i]);
counter+=1;
}
for(j=0;j<10;j++)
{
if((sum+j)%11==0)
{
break;
}
}
return x+""+j;
}
public static void main(String args[])
{
String a = "020131452";
System.out.println(ISBN(a));
}
}
Hope this helps.
This works:
public static int ISBN(String nineDigitNum){
int sum = 0;
for(int i = 0; i<nineDigitNum.length(); i++){
sum += Integer.parseInt(""+nineDigitNum.charAt(i))*(10-i);
}
return (sum%11);
}
Also I believe if the checksum is == to 10, it should return an X, so you could either change the return type and add an if statement somewhere, or just put the if statement outside wherever you are using this method.
Here is a short one without loops that uses only substring(), charAt() and length():
public static String ISBN(String nineDigits) {
int chkD = 11 - checkDigit(nineDigits, 0);
return nineDigits + ((chkD == 10) ? "X" : chkD);
}
public static int checkDigit(String nDsub, int chkD) {
if (nDsub.length() == 0)
return 0;
chkD = ((nDsub.charAt(0) - '0') * (nDsub.length() + 1));
return (chkD + checkDigit(nDsub.substring(1), chkD)) % 11;
}
Output:
> ISBN("123456789")
"123456789X"
> ISBN("123456780")
"1234567806"