Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

The method isPrime() is undefined for the type String

$
0
0
Code:
class MyInteger {
	//Intialize value
	int value;
	
	//Value Constructor
	MyInteger(int number) {
		value = number;
	}
	
	//GetValue Method
	public int getValue() {
		return value;
	}
	
	//isEven Method
	public static boolean isEven(int n) {
		return (n % 2 == 0);
	}
	
	//isOdd Method
	public static boolean isOdd(int n) {
		return !isEven(n);
	}
	
	//isPrime Method
	public static boolean isPrime(int n) {
		for(int f = 2; f < n/2; f++) {
			if(n % f == 0) {
				return false;
			}
		}
		return true;
	}
	
	//isEven
	public static boolean isEven(MyInteger n) {
		return n.isEven();
	}
	
	//isOdd
	public static boolean isOdd(MyInteger n) {
		return n.isOdd();
	}
	
	//isPrime
	public static boolean isPrime(MyInteger n) {
		return n.isPrime();
	}
	
	//Method isEven checks
	public boolean isEven() {
		return isEven(value);
	}
	
	//Method isOdd checks
	public boolean isOdd() {
		return isOdd(value);
	}
	
	//Method isPrime checks
	public boolean isPrime() {
		return isPrime(value);
	}
	
	//Method equals checks
	public boolean equals(int n) {
		return (value == n);
	}
	
	public boolean equals(MyInteger n) {
		return equals(n.getValue());
	}
	
	//Reads string and returns
	public static int parseInt(String s) {
		return Integer.parseInt(s);
	}
	
	public static int parseInt(char[] s) {
		return parseInt(new String(s));
	}
} // Class end


Test Code:
import java.util.Scanner;
public class TestMyInteger {
public static void main(String[] args) {
	
	//User input
	Scanner input = new Scanner(System.in);
	System.out.println("Enter a number: ");
	int a = input.nextInt();
	
	//Create object
	MyInteger i1 = new MyInteger(a);
	
	//Display output
	System.out.println(a + " is even? " + i1.isEven());
	System.out.println(a + " is odd? " + i1.isOdd());
	System.out.println(a + " is prime? " i1.isPrime());
	System.out.println("17 is prime? " + MyInteger.isPrime(17));

	char[] c ={'1', '2', '3', '4'};
	System.out.println("Characters " + MyInteger.parseInt(c));
	String s ="123456789";
	
	System.out.println("String is " + MyInteger.parseInt(s));
	System.out.println("19 is odd? " + MyInteger.isOdd(19));
	System.out.println("10 is even? " + MyInteger.isEven(10));
	System.out.println(a + " is equal to 24? " + i1.equals(24));
}
}


Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	Syntax error on token "i1", delete this token
	The method isPrime() is undefined for the type String

	at TestMyInteger.main(TestMyInteger.java:16)

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>