Simple Java Method Error when Returning - java

I'm learning methods and was trying to write code that basically tells if a number is prime. However, I keep encountering the error:
error: cannot find symbol
return(isPrime);
^
error: illegal start of type
return(isPrime);
This is my current code (i hope i'm using the method correctly):
import java.util.Scanner;
public class DoublePalindromicPrimes{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("Please enter a number:");
int n = in.nextInt();
//prime(n);
boolean resultPrime = prime(n);
if (resultPrime){
System.out.println("This is a prime");
}
else {
System.out.println("This is not a prime");
}
}
public static boolean prime(int x){
for (int i=2;i<x;i++){
boolean isPrime;
if (x%i==0){
isPrime=false;
}
else{
isPrime=true;
}
}
return isPrime;
}
}
Any help is appreciated!

public static boolean isPrime(int x)
{
if(x > 2) {
if(x%2 == 0) {
return false;
} else {
int sqrt = (int)(Math.sqrt(x));
for(int i=3;i<=sqrt;i+=2) {
if(x%i == 0) {
return false;
}
}
}
return true;
} else if(x==2) {
return true;
} else { //1, 0, and negatives
return false;
}
}

change it to
return isPrime;
note the space and make declaration out of isPrime for loop

You declared isPrime inside your loop, so the return statement can't see it. Move it outside the loop.

public static boolean prime(int x) //throws InvalidNumberException
{
if (x <= 0)
{
//throw new InvalidNumberException("The number is invalid");
}
int squareRoot = (int)(Math.sqrt(x));
for (int i = 2; i <= squareRoot; i++)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
This is an optimized prime validator.

Related

What is wrong with the logic of following code?

The following code gives only two outputs (2 and 3), after this it gets terminated, why doesn't it continue?
public class PrimeSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
boolean prime = true;
for(int i=2;i<=N;i++) {
for(int j=2;j*j<=i;j++) {
if(i%j == 0) {
prime = false;
break;
}
}
if(prime == true) {
System.out.println(i);
}
}
}
}
The code you provided doesn't work because you never made the variable boolean prime true again
So just make the boolean back to true again after every iteration of the inner for loop.
public class PrimeSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
boolean prime = true;
for(int i=2;i<=N;i++) {
// ADD THIS LINE
prime = true;
for(int j=2;j*j<=i;j++) {
if(i%j == 0) {
prime = false;
break;
}
}
if(prime == true) {
System.out.println(i);
}
}
}
}
That is it! 😁

Java Program: return statements not working

This program creates various methods for a class and runs each method. When I run the methods, the return statements do not work in the methods, although the integer value entered is definitely passed to the object (I tested with a print statement). I am sure the issue is somewhere with my static declarations.
can anyone help?
import java.util.Scanner;
public class MyInteger {
public static int storedValue;
public int value;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Class with various methods test. Please enter an integer:");
int num = input.nextInt();
MyInteger x = new MyInteger(num);
storedValue = x.value;
System.out.println("Now performing returnInt");
x.returnInt();
System.out.println("Now performing isEven");
x.isEven();
}
MyInteger(int a){
value = a;
}
public int returnInt(){
return storedValue;
}
public boolean isEven(){
if(value % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(){
if(value % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(){
if (value == 2){
return true;
}
for (int i = 2; i < value;i++){
if (value % i == 0){
return false;
}
}
return true;
}
public boolean isEven(int a){
if (a % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(int a){
if (a % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(int a){
if (a == 2){
return true;
}
for (int i = 2; i < a;i++){
if (a % i == 0){
return false;
}
}
return true;
}
public boolean isEven(MyInteger a){
if (a.value % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(MyInteger a){
if (a.value % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(MyInteger a){
if (a.value == 2){
return true;
}
for (int i = 2; i < a.value;i++){
if (a.value % i == 0){
return false;
}
}
return true;
}
public boolean equals(int a){
if (value == a){
return true;
}
else{
return false;
}
}
public boolean equals(MyInteger a){
if (value == a.value){
return true;
}
else{
return false;
}
}
public int parseInt(String s, int radix){
for (int i = (s.length()-1); i >= 0; i--){
radix += (int)s.charAt(i)*(Math.pow(10, i));
}
return radix;
}
}
First, remove the static storedvalue.
// public static int storedValue;
Then change your returnInt to return the value. Like,
public int returnInt(){
return value;
}
Finally, assign the return(ed) value in your caller (main, or use it directly). Something like
System.out.println("Now performing returnInt");
int v = x.returnInt();
System.out.printf("Value = %d%n", v);
System.out.println("Now performing isEven");
if (x.isEven()) {
System.out.println("It's even");
} else {
System.out.println("It's odd");
}

How do I make this output a boolean?

So here's my code, I want the output to be like this:
Given two numbers, is the second input a multiple of the first?
For Example:
Input:
3
6
Output:
true
public boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
When I try it I get an error, I think it's because the return statement is within the if and else statements.
The code is perfectly fine .. Error must be Somewhere else
public class Test1 {
public static void main(String[] args) {
System.out.println(multiple(3, 9));
}
public static boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
}
Output
true
here is output see IDEONE
The easiest way is to return the result of your if statement.
return n % m == 0;
I'm not sure what i/j are doing. You don't use them except to increment, but they are local to the function and get GC'd after the return. What you have now is basically this:
boolean bool = some_calculation();
if (bool == true)
{
return true;
}
else
{
return false;
}

Recursive method to add odd numbers

I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}

Creating a recursive method for Palindrome

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:
public static void main (String[] args){
System.out.println(isPalindrome("noon"));
System.out.println(isPalindrome("Madam I'm Adam"));
System.out.println(isPalindrome("A man, a plan, a canal, Panama"));
System.out.println(isPalindrome("A Toyota"));
System.out.println(isPalindrome("Not a Palindrome"));
System.out.println(isPalindrome("asdfghfdsa"));
}
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() == 1 ) return true;
in= in.toUpperCase();
if(Character.isLetter(in.charAt(0))
}
public static boolean isPalindromeHelper(String in){
if(in.equals("") || in.length()==1){
return true;
}
}
}
Can anyone supply a solution to my problem?
Here I am pasting code for you:
But, I would strongly suggest you to know how it works,
from your question , you are totally unreadable.
Try understanding this code. Read the comments from code
import java.util.Scanner;
public class Palindromes
{
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
// if length =0 OR 1 then it is
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
// check for first and last char of String:
// if they are same then do the same thing for a substring
// with first and last char removed. and carry on this
// until you string completes or condition fails
return isPal(s.substring(1, s.length()-1));
// if its not the case than string is not.
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("type a word to check if its a palindrome or not");
String x = sc.nextLine();
if(isPal(x))
System.out.println(x + " is a palindrome");
else
System.out.println(x + " is not a palindrome");
}
}
Well:
It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
In the first method, why are you testing for testing for a single space or any single character?
You might want to consider generalizing your termination condition to "if the length is less than two"
Consider how you want to recurse. One option:
Check that the first letter is equal to the last letter. If not, return false
Now take a substring to effectively remove the first and last letters, and recurse
Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.
I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() < 2 ) return true;
if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
return isPalindrome(in.substring(1,in.length-2));
else
return false;
}
Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.
I think, recursion isn't the best way to solve this problem, but one recursive way I see here is shown below:
String str = prepareString(originalString); //make upper case, remove some characters
isPalindrome(str);
public boolean isPalindrome(String str) {
return str.length() == 1 || isPalindrome(str, 0);
}
private boolean isPalindrome(String str, int i) {
if (i > str.length / 2) {
return true;
}
if (!str.charAt(i).equals(str.charAt(str.length() - 1 - i))) {
return false;
}
return isPalindrome(str, i+1);
}
Here is my go at it:
public class Test {
public static boolean isPalindrome(String s) {
return s.length() <= 1 ||
(s.charAt(0) == s.charAt(s.length() - 1) &&
isPalindrome(s.substring(1, s.length() - 1)));
}
public static boolean isPalindromeForgiving(String s) {
return isPalindrome(s.toLowerCase().replaceAll("[\\s\\pP]", ""));
}
public static void main(String[] args) {
// True (odd length)
System.out.println(isPalindrome("asdfghgfdsa"));
// True (even length)
System.out.println(isPalindrome("asdfggfdsa"));
// False
System.out.println(isPalindrome("not palindrome"));
// True (but very forgiving :)
System.out.println(isPalindromeForgiving("madam I'm Adam"));
}
}
public class palin
{
static boolean isPalin(String s, int i, int j)
{
boolean b=true;
if(s.charAt(i)==s.charAt(j))
{
if(i<=j)
isPalin(s,(i+1),(j-1));
}
else
{
b=false;
}
return b;
}
public static void main()
{
String s1="madam";
if(isPalin(s1, 0, s1.length()-1)==true)
System.out.println(s1+" is palindrome");
else
System.out.println(s1+" is not palindrome");
}
}
Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:
private static boolean isPalindrome(String str, int left, int right) {
if(left >= right) {
return true;
}
else {
if(str.charAt(left) == str.charAt(right)) {
return isPalindrome(str, ++left, --right);
}
else {
return false;
}
}
}
public static void main(String []args){
String str = "abcdcbb";
System.out.println(isPalindrome(str, 0, str.length()-1));
}
Here are three simple implementations, first the oneliner:
public static boolean oneLinerPalin(String str){
return str.equals(new StringBuffer(str).reverse().toString());
}
This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:
public static boolean isPalindrome(String str){
if(str.isEmpty()) return true;
int last = str.length() - 1;
for(int i = 0; i <= last / 2;i++)
if(str.charAt(i) != str.charAt(last - i))
return false;
return true;
}
And recursively:
public static boolean recursivePalin(String str){
return check(str, 0, str.length() - 1);
}
private static boolean check (String str,int start,int stop){
return stop - start < 2 ||
str.charAt(start) == str.charAt(stop) &&
check(str, start + 1, stop - 1);
}
public static boolean isPalindrome(String str)
{
int len = str.length();
int i, j;
j = len - 1;
for (i = 0; i <= (len - 1)/2; i++)
{
if (str.charAt(i) != str.charAt(j))
return false;
j--;
}
return true;
}
Try this:
package javaapplicationtest;
public class Main {
public static void main(String[] args) {
String source = "mango";
boolean isPalindrome = true;
//looping through the string and checking char by char from reverse
for(int loop = 0; loop < source.length(); loop++){
if( source.charAt(loop) != source.charAt(source.length()-loop-1)){
isPalindrome = false;
break;
}
}
if(isPalindrome == false){
System.out.println("Not a palindrome");
}
else
System.out.println("Pailndrome");
}
}
String source = "liril";
StringBuffer sb = new StringBuffer(source);
String r = sb.reverse().toString();
if (source.equals(r)) {
System.out.println("Palindrome ...");
} else {
System.out.println("Not a palindrome...");
}
public class chkPalindrome{
public static String isPalindrome(String pal){
if(pal.length() == 1){
return pal;
}
else{
String tmp= "";
tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));
return tmp;
}
}
public static void main(String []args){
chkPalindrome hwObj = new chkPalindrome();
String palind = "MADAM";
String retVal= hwObj.isPalindrome(palind);
if(retVal.equals(palind))
System.out.println(palind+" is Palindrome");
else
System.out.println(palind+" is Not Palindrome");
}
}
Here is a recursive method that will ignore specified characters:
public static boolean isPal(String rest, String ignore) {
int rLen = rest.length();
if (rLen < 2)
return true;
char first = rest.charAt(0)
char last = rest.charAt(rLen-1);
boolean skip = ignore.indexOf(first) != -1 || ignore.indexOf(last) != -1;
return skip || first == last && isPal(rest.substring(1, rLen-1), ignore);
}
Use it like this:
isPal("Madam I'm Adam".toLowerCase(), " ,'");
isPal("A man, a plan, a canal, Panama".toLowerCase(), " ,'");
It does not make sense to include case insensitivity in the recursive method since it only needs to be done once, unless you are not allowed to use the .toLowerCase() method.
there's no code smaller than this:
public static boolean palindrome(String x){
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
if you want to check something:
public static boolean palindrome(String x){
if(x==null || x.length()==0){
throw new IllegalArgumentException("Not a valid string.");
}
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
LOL B-]
public static boolean isPalindrome(String p)
{
if(p.length() == 0 || p.length() == 1)
// if length =0 OR 1 then it is
return true;
if(p.substring(0,1).equalsIgnoreCase(p.substring(p.length()-1)))
return isPalindrome(p.substring(1, p.length()-1));
return false;
}
This solution is not case sensitive. Hence, for example, if you have the following word : "adinida", then you will get true if you do "Adninida" or "adninida" or "adinidA", which is what we want.
I like #JigarJoshi answer, but the only problem with his approach is that it will give you false for words which contains caps.
Palindrome example:
static boolean isPalindrome(String sentence) {
/*If the length of the string is 0 or 1(no more string to check),
*return true, as the base case. Then compare to see if the first
*and last letters are equal, by cutting off the first and last
*letters each time the function is recursively called.*/
int length = sentence.length();
if (length >= 1)
return true;
else {
char first = Character.toLowerCase(sentence.charAt(0));
char last = Character.toLowerCase(sentence.charAt(length-1));
if (Character.isLetter(first) && Character.isLetter(last)) {
if (first == last) {
String shorter = sentence.substring(1, length-1);
return isPalindrome(shorter);
} else {
return false;
}
} else if (!Character.isLetter(last)) {
String shorter = sentence.substring(0, length-1);
return isPalindrome(shorter);
} else {
String shorter = sentence.substring(1);
return isPalindrome(shorter);
}
}
}
Called by:
System.out.println(r.isPalindrome("Madam, I'm Adam"));
Will print true if palindrome, will print false if not.
If the length of the string is 0 or 1(no more string to check), return true, as the base case. This base case will be referred to by function call right before this. Then compare to see if the first and last letters are equal, by cutting off the first and last letters each time the function is recursively called.
Here is the code for palindrome check without creating many strings
public static boolean isPalindrome(String str){
return isPalindrome(str,0,str.length()-1);
}
public static boolean isPalindrome(String str, int start, int end){
if(start >= end)
return true;
else
return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}
public class PlaindromeNumbers {
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
/**
* Function to check a String is palindrome or not
* #param s input String
* #return true if Palindrome
*/
public boolean checkPalindrome(String s) {
if (s.length() == 1 || s.isEmpty())
return true;
boolean palindrome = checkPalindrome(s.substring(1, s.length() - 1));
return palindrome && s.charAt(0) == s.charAt(s.length() - 1);
}
Simple Solution
2 Scenario --(Odd or Even length String)
Base condition& Algo recursive(ch, i, j)
i==j //even len
if i< j recurve call (ch, i +1,j-1)
else return ch[i] ==ch[j]// Extra base condition for old length
public class HelloWorld {
static boolean ispalindrome(char ch[], int i, int j) {
if (i == j) return true;
if (i < j) {
if (ch[i] != ch[j])
return false;
else
return ispalindrome(ch, i + 1, j - 1);
}
if (ch[i] != ch[j])
return false;
else
return true;
}
public static void main(String[] args) {
System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));
}
}
for you to achieve that, you not only need to know how recursion works but you also need to understand the String method.
here is a sample code that I used to achieve it: -
class PalindromeRecursive {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String input=sc.next();
System.out.println("is "+ input + "a palindrome : " + isPalindrome(input));
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
isPalindrome(s.substring(low++,high--));
}
return true;
}
}

Categories

Resources