Pretty simple question I'm sure, since I'm only just learning.
In a larger class that I am on my way of implementing, we have to provide a method Max to return the maximum value in an array. This is what I have:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
return Max;
}
}
However, the method does not compile. I believe it has something to do with the return type. The program calls up this function (and a similar Min function) like this further on in the program:
System.out.println("[" + window.Min() + " " + window.Max() + "]");
What am I doing wrong?
EDIT: Thanks for all of your answers! Just started learning coding, so trivial mistakes like this one can still cause a whole lot of frustration. Saving my ass, all of you!
Java always considers the possibility of the for loop not being entered, and sees no return statement at the end of the method, giving a missing return statement compiler error. The method is declared to return something, an int, so every possible execution path must return something.
Move return Max; after the end of the for loop, both to satisfy the compiler and to provide a correct "find the max" method.
Incidentally, Java variables usually have a lowercase first letter per normal conventions. The Max variable should be called max. The same applies to the name of the Max method.
I believe this does not compile because there's a way you can get to the end of the method without an explicit return statement.
You need to put that return Max; at the bottom, as opposed to inside the for loop:
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
The return statement should not be in the for loop.
It should be
public static int Max(int[] window){
//assume length of array window > 0
int Max = window[0];
for (int i = 1; i < window.length; i++){
if (window[i] > Max) {
Max = window[i];
}
}
return Max;
}
It doesn't compile because it is possible to get to the end of the method without anything being returned. If the length of the array is 0 or 1 the loop will not be entered and the return not executed.
Related
Which is better to use for an array of millions of integers(ages)
public static int findMax(int[] x) {
int max = 0;
int curr = 0;
for (int a : x) {
curr = Math.max(curr, a);
max = Math.max(max, curr);
}
return max;
}
public static int findMax(int[] x){
List<Integer> list = new ArrayList<>();
for (int y : x){
list.add(y);
}
return Collections.max(list);
}
The first one will definitely be faster than the second one, as you really don't want to be making an arraylist for no reason just to find the maximum of an array!
Also, there is no reason to use two different variables for the current and the max, just the max will suffice, like so:
public static int findMax(int[] x) {
int max = Integer.MIN_VALUE;
for (int a : x) {
max = Math.max(max, a);
}
return max;
}
Note: I used the minimum integer because the largest value in your array may be negative. Also, you could just use an if-condition instead of Math.max(), but it'll work either way. This also saves you an extra operation. The runtime is O(n) in every case.
They both look like they are O(n). You could always use a logger and see what the time is. The following is a link that talks about logging time executed: How do I time a method's execution in Java?
EDIT: Got it working. Still not sure what the weird issue was, but I think it had to do with the fact that I had a loop and recursion.
I don't fully understand the question. but you don't need both, a while loop and recursion. Recursion alone is sufficient here. Use a simple if statement to stop recursion when the number is fully printed.
Note that recursion simplifies putting the digits in the right order here -- with a while loop, you'd need to reverse them somehow...
public static void printInBinary (int num) {
int div = num % 2;
int rem = num / 2;
if (rem > 0) {
printInBinary(rem);
}
System.out.print(div);
}
Your while loop is continuously going because your num-- isn't in the loop, so the number never changes.
public static void printInBinary (int num)
{
int div = (Integer)num%2;
int rem = (Integer)num/2;
while (num >= 1)
{
System.out.print(div);
printInBinary(rem);
num--;//Moved here
}
//removed from here
}
So I need to develop a method to find the smallest digit in an integer.
Here is my implementation
public int find(int n){
if(n < 10) return n;
return Math.min(n%10, find(n/10));
}
You can change the int by long ...
If you're interested in learning how to figure this out yourself (and you should be), I would try following these steps.
Do the process in your head, slowly - or even better, write the steps on paper! Take notice of each step you take.
Step one may be: look at the first digit
Consider the steps you've created. Are there parts which seem to be repeating themselves? These parts will likely be your recursive function.
Rewrite the steps as a recursive function (in plain English)
Translate the steps into your programming language; Java, in this case.
If you want, you can even leave the plain english steps in your code behind each line as comments, so everyone can easily follow your code
Personally I think a for loop would be quicker and easier than a recursive function. But for recursion or a for loop you need something to iterate on. Easiest way is to convert the number to a string and then iterate through it doing needed comparisons.
In your main:
int i = 578329;
String s = Integer.toString(i);
s = FindSmallest(s);
Call the function:
private String FindSmallest(String s){
if(s.length() <= 1)
return s;
String sFirstChar = s.substring(0,1);
String sSecondChar = s.substring(1,2);
int iFirst = Integer.parseInt(sFirstChar);
int iSecond = Integer.parseInt(sSecondChar);
if(iFirst < iSecond)
return FindSmallest( sFirstChar + s.substring(2));
else
return FindSmallest(sSecondChar + s.substring(2));
}
public static int find(int num) {
if(num < 10){
return num;
}
int d = num % 10;
int pmin = find(num / 10);
return (d <= pmin) ? d : pmin;
}
You can also write:
public static int minDigit(int n, int min){
if(n!=0) {
if(n%10 < min) {
min = n%10;
}
return minDigit(n/10, min);
}
return min;
}
I just created a code which represents the sum of integer values from 1 to 10.
public class ArithmeticProgress {
public static void main(String args[]) {
int i = 10;
int n;
System.out.println(arithmeticprogress(n, i));
}
static int arithmeticprogress(int n, int i) {
int result = n;
for (n = 0; n < i; n++)
result += result;
return result;
}
}
Unfortunately, it does not compile and therefore it only shows error. Can somebody tell me how to correct this code? Thank you!
You need to initialize n here.
int n=10; // initialize n to some value
System.out.println(arithmeticprogress(n, i)); //else you will get error here
Use IDE to coding. Then you will get
int n;
System.out.println(arithmeticprogress(n, i));//'n' might not be initialize
Or else you can use n as class level variable. Then it will set to it's default value.
As int n; declare in method main, it won't be initialized as it is a local variable and local variable are not initialized automatically. You need to initialize it explicitly before use. So changing it to int n=0; will work.
You are getting compilation error because in java local variables are stack variables and they must be initialized before they can be used. In your case variable n is used before it is initialized. Initialized it like this and it should work.
int n= 1;
There are two problem in your code.
1. You must need to initialize local variable before to use it. You need to initialize n to 0 or any other value which is applicable for your logic.
2. If you want to get the sum of integer from 1 to 10 than your logic is incorrect that's why you got 1024 as a result ( If you initialize n=1 ). you are adding your current result to previous result which is incorrect. To simply add integer from 1 to 10 i think you didn't need variable n in you code.
For this your method should be as shown below :
static int arithmeticprogress(int i) {
int result = 0;
for (int n = 1; n <=i; n++)
result = result + n;
return result;
}
It will gives you result as 55 which is summation of 1 to 10 integer number.
May this will help you.
My algorithm is suppose to tell me if 'x'(which has the value 5) is in the sorted array. However, I keep getting a 0. Well since my condition states that if 'x' is not in the array show 0. Where am I going wrong?
import java.util.Arrays;
public class binarySeacg {
public static void main (String[]args)
{
int[] array = {10,7,11,5,13,8};
exchangesort(array);
binsearch(array,5);
System.out.println(Arrays.toString(array));
}
public static void exchangesort(int[] S)
{
int i,j,temp;
for(i=0;i<S.length;i++)
for(j=i+1;j<S.length;j++)
if(S[i]>S[j])
{
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
}
public static int binsearch(int[] S, int x)
{
int location, low, high, mid;
low = 1; high = S.length;
location = 0;
while(low<=high && location==0)
{
mid =(low + high)/2;
if(x== S[mid])
location = mid;
else if(x < S[mid])
high = mid -1;
else
low = mid + 1;
}
System.out.println(location);
return location;
}
}
You set low = 1;, and 5 is the minimal element - so it is in index 0 - so in the sublist of [1,S.length] - it is indeed not there.
You should set low = 0;, and start from the first element - not the second. (Remember that index in java starts from 0, not 1).
(PS, note that in this specific case - the algorithm is correct, since in the sorted list - 5 is in the index 0).
Here you are sorting an array and then the sorted array is used for searching the element.
And if the search is successful, then you do the below assignment
location = mid; which means you are assigning the matching element's index to the location variable.
In this case, element 5 is in 0th index.
Hence you are always getting 0 on your STDOUT
Because, you are trying to find x value, which you are passing 3 and in your list. It is not present. So, change it to other value like 5 and then try.
Also, you should start low=0 instead of low=1. Because, it will miss the first element all the time.
public static int binsearch(int[] S, int x)
{
int location, low, high, mid;
low = 0; high = S.length;
location = 0;
while(low<=high && location==0)
{
mid =(low + high)/2;
if(x == S[mid])
{
location = mid;break;
}
else if (x < S[mid])
{
high = mid - 1;
} else
{
low = mid + 1;
}
}
System.out.println(location);
return location;
}
Note : For the different output, change the value binsearch(array,5); here, which is called from main() method. Remember, change the value, which are present in your list.
in java and most languages, the index starts from 0, not 1, and ends at n-1, not n
for binary search, check carefully about when exiting the while loop, and always remember the meaning of your low and high variables, whether it is [low, high], or [low, high)
for this specific problem, u should also consider what if there r duplicates in the array. whether to return the first element or anyone in the array