How to control parameter in method in java - java

I have a very easy question but I don’t know what. The sample code below
public class test {
public static void main(String[] args) {
test test = new test();
int temp = test.method(0);
System.out.println("temp = " + temp);
}
public int method(int i) {
if (i < 7) {
i++;
method(i);
}
return i;
}
}
If I want get 7 in the temp in the main what can I do? Just use the other static parameter? or is there any way to achieve this one?

public int method(int i) {
if (i < 7) {
i++;
return method(i);
} else {
return i;
}
}
should work fine :)
breakdown:
IF i is smaller than 7, increment i and return method(i)
ELSE return i (must be 7)
the else block is optional:
public int method(int i) {
if (i < 7) {
i++;
return method(i);
}
return i;
}
but it's more clear if you have the else since it is conditional.

Related

function to find number of ways u can split n objects using parts up to m

I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}

why Am i getting this error of 'missing return statement'? [duplicate]

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 2 years ago.
import java.util.Arrays;
public class Solution {
public static int findDuplicate(int[] arr) {
int n=arr.length;
Arrays.sort(arr);
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
return arr[i];
}
}
}
}
The problem is that you don't return anything if the logic does not enter in the "if". Consider adding a default value to return.
You can change the code like this
package com.stackoverflow.question;
import java.util.Arrays;
public class Solution {
public static int findDuplicate(int[] arr) {
int n = arr.length;
Arrays.sort(arr);
for (int i = 0; i < n - 1; i++) {
if (arr[i] == arr[i + 1]) {
return arr[i];
}
}
return 0; //Default value to return
}
}
You need to handle the case where there are no duplicates. You can either return -1, which is a convention used in places like String.indexOf, or you could throw an Exception, such as NoSuchElementException
public static int findDuplicate(int[] arr) {
int n=arr.length;
Arrays.sort(arr);
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
return arr[i];
}
}
return -1;
}
That is because if your arr[i]==arr[i+1] never is true, the function is not going to return anything, but it has to return something, so:
public static int findDuplicate(int[] arr) {
int n=arr.length;
Arrays.sort(arr);
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
return arr[i];
}
}
return -1;//If if the is stament is never true
}

Recursive Java Method

I have this small block of code used to find the sum of certain numbers:
public class TestClass {
public static int sumOfNums(int num[], int int) {
if(int == num.length-1) return int;
else if( (num[int]%2==0) || num[int] <= 0 ) {
return num[int] + sumOfNums(num, int+1); }
else return 0 + sumOfNums(num, int+1);
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumOfNums(arr, 0));
}
}
However, whenever I run the print statement I get the exception:
Exception in thread "main" java.lang.StackOverflowError
at TestClass.sumOfNums(TestClass.java:13)
at TestClass.sumOfNums(TestClass.java:10)
Can anybody help me?
As another user said, your recursion is never ending.
Changing arr[head-1] to head-1 should fix this problem on this line:
else return 0 + sumNegEven(arr, arr[head-1]);
and changing it here as well:
return arr[head] + sumNegEven(arr, arr[head-1]); }
public class TestClass {
public static int sumNegEven(int arr[], int head) {
if(head == 0) {
return 0;
} else if( arr[head]%2==0 || arr[head] <= 0 ) {
return arr[head] + sumNegEven(arr, head-1);
} else {
return 0 + sumNegEven(arr, head-1);
}
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumNegEven(arr, arr.length-1));
}
}
By call calling the arr[head-1] you were calling value of the index not index and they last long because recursion is not terminated. If you calling head-1, you are calling actual index and will get answer 21 without exception.
this won't process the first item in the array
if(head == 0) {
return 0;
}
you will have to change it to
if(head < 0) {
return 0;
}

How to find the most common character in a String

I have a quick question. How would I find the most common character in a string in Java. I know logically how to do it, but I am not sure if my syntax in correct:
public class HelloWorld {
public static void main(String[] args){
String votes = "ABBAB";
char[] StoringArray = votes.toCharArray();
int numOFB = 0;
int numOFA = 0;
if (StoringArray.contains("A")) {
numOFA++;
} else if (StoringArray.contains("B")) {
numOFAB++;
}
if (numOFA = numOFB) {
System.out.println("Tie");
} else if (numOFA > B) {
System.out.println("A");
} else {
System.out.println("B");
}
}
}
Could anyone help me with how to correctly do this in Java?
You can not compare char Array with string, below logic should work and give you what you need:
public static void main(String[] args){
String votes = "ABBAB";
char[] storingArray = votes.toCharArray();
int numOFB = 0;
int numOFA = 0;
for(char c : storingArray) {
if(c == 'A') {
numOFA++;
}
if(c == 'B') {
numOFB++;
}
}
if (numOFA == numOFB) {
System.out.println("Tie");
} else if (numOFA > numOFB) {
System.out.println("A");
} else {
System.out.println("B");
}
}
There are couple of mistakes in your code:
You can not use if (numOFA = numOFB) it is not valid expression. You should use == to compare
You can not compare char Array with contains method. It should be used on String object
As the comments said; it looks like you're counting the number of A's or B's, not the longest substring. Are you only analyzing a String composed of A's and B's?
Also, you're using = to check for equality when you should be using ==. I would recommend using an IDE like Eclipse which would show you when you're doing this.
Edit: also, you're not looping through the array. You're just checking if the String contains an A or a B and adding 1 if it does. You need to loop through the entire array.
Actually, I was working with it, and I found this is the nicest way to do it:
String votes = "ABBAB";
char[] StoringArray = votes.toCharArray();
int B = 0;
int A = 0;
for (int i = 0; i < StoringArray.length; i ++) {
if (StoringArray[i] == 'A') {
A++;
} else if (StoringArray[i] == 'B') {
B++;
}
}
if (A == B) {
System.out.println("Tie");
} else if (A > B) {
System.out.println("A");
} else {
System.out.println("B");
}
I would give you a more abstract solution:
public class Counter{
private char c;
private int count;
Counter(char c, int count){
this.c=c;
this.count=count;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public int getCount() {
return count;
}
public void addOcurrence() {
this.count++;
}
#Override
public boolean equals(Object obj) {
if(obj!=null)
if(((Counter)obj).getC()== this.c)
return true;
return false;
}
}
public static void main(String[] args){
String votes = "whateveryouwanttoputhereorcanbefromaparameter";
char[] storingArray = votes.toCharArray();
List<Counter> listCounter = new ArrayList<Counter>();
for(char aChar : storingArray){
Counter compareCounter = new Counter(aChar,1);
if(listCounter.contains(compareCounter)){
listCounter.get(listCounter.indexOf(compareCounter)).addOcurrence();
}else{
listCounter.add(compareCounter);
}
}
Counter max = listCounter.get(0);
for( Counter c : listCounter){
if(c.getCount() > max.getCount()){
max = c;
}
}
System.out.println("the character with more ocurrence is: "+max.getC());
}

Java class won't compile

Im quite the novice when it comes to programming and im trying to translate this PHP algorithm to Java.
function isPrime($n)
{
$i = 2;
if ($n == 2) {
return true;
}
while ($i < $n) {
if ($n % $i == 0) {
return false;
}
$i++;
}
return true;
}
for ($i = 3; $i < 100; $i++) {
if (isPrime($i)) {
echo $i;
}
}
The only thing i've come up with so far is this.
public class Primtal {
public static boolean isPrime(int n)
{
int i = 2;
if (n == 2) {
return true;
}
while (i < n) {
if ( n % i == 0) {
return false;
}
i++;
}
return true;
}
for(int i = 3; i < 1000; i++){
if (isPrime(i)) {
System.out.print(i);
}
}
}
I realize this look really stupid but i really need to get this to work. I think the problem lies mostly with the for loop as im currently getting the error illegal start of type there. Im not really sure how to translate this to Java and i would appreciate any help i can get.
I believe the problem with your code is that you've put a for loop in the middle of class declaration, which is incorrect - it needs to be inside some method. It seems logical in this case to put it in main(), so it's executed when you run your program. Maybe something like this:
public class Primtal
{
public static boolean isPrime(int n)
{
int i = 2;
if(n == 2)
{
return true;
}
while(i < n)
{
if(n % i == 0)
{
return false;
}
i++;
}
return true;
}
public static void main(String[] args)
{
for(int i = 3; i < 1000; i++)
{
if(isPrime(i))
{
System.out.print(i);
}
}
}
}
(Note the addition of public static void main(String[] args) in the second half of the code.)
Oracle has official tutorials on how Java programs need to be structured, and other basics of the language. You can find the one related to the main method here. Or, to start from the beginning, the full tutorial starts here.
you can't write the for loop
for(int i = 3; i < 1000; i++){
if (isPrime(i)) {
System.out.print(i);
}
}
directly inside a class.
i believe what you wish to do is to have a main method, in which you can have the for loop
Your for loop needs to be within a method of some sort,so you can put it in the main method:
public class Primtal {
public static void main(String [] args)
{
for(int i = 3; i < 1000; i++)
{
if (isPrime(i)) {
System.out.print(i);
}
}
public static boolean isPrime(int n)
{
int i = 2;
if (n == 2) {
return true;
}
while (i < n) {
if ( n % i == 0) {
return false;
}
i++;
}
return true;
}
}
The problem is that your for loop isn't in a method. Enclose it in a main method.
public static void main(String[] args) {
// Your for loop here
}
Also, change print to println, or else all the numbers will appear concatenated together on one line.

Categories

Resources