I am very new at java coding. I am having difficulty finding out how to link my main method with the method that determines if a value is prime. When I run the code below in eclipse, the method doesn't seem to execute at all. Does anyone know what I did wrong?
Also, for the last part I was thinking of having System.out print whether the input value is prime or not. ie true or false would be fine.
import java.util.*;
class IsPrime {
public boolean isprime(int n) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n1 = input1.nextInt();
int i,c=0;
for(i=1;i<=n1;i++) {
if(n1%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
System.out.println("Your number is:")
}
}
The line
System.out.println("Your number is:")
is unreachable as you have an
else {
return false;
}
before it.
First of all, what it's said by Strawberry and appclay is right.
In the other hand, your method isprime is an instance method whilst your main (I guess you talk about the method of your main class) is a class (static) method.
Try the following:
public static void main(String[] args) {
int possiblePrime = // initialise your parameter
IsPrime isPrime = new IsPrime();
boolean primeOrNot = isPrime.isprime(possiblePrime);
System.out.println("Your number is prime: " + primeOrNot);
}
Change your method to static and you can reference it without creating an instance of that class
public static boolean isprime(int n) {
If I understand what you're looking to is implement an isprime method and call it in a main.
class IsPrime {
public boolean isPrime(int n) {
int i,c=0;
for(i=1;i<=n;i++) {
if(n%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n = input1.nextInt();
IsPrime isPrime = new IsPrime();
System.out.println("Your number is prime: " + isPrime.isPrime(n));
}
}
That should do what you want to do. However, there is a bug in your code.
What you have will return true for all numbers not just prime numbers. I'll leave it up to you to spot the bug and the fix.
EDIT: No bug. See below comments.
Related
The number is given and we need to find if it is a square number or triangle number?
This "num" should 1st verify the square method then it has to go for triangle method.
there issue is: how can i call from square to triangle or any other methed to call the Triangle method if my square method won't suit.
Here's my code:
public class HelloWorld{
public static void main(String []args){
class Number{
int num;
public boolean isSquare(){
int squareNumber=1;
while(squareNumber<num){
squareNumber = num*num;
}
if(squareNumber%num==0)
{
System.out.println(num+" is a Square number");
}
else
{
return isTriangle();
}
boolean isTriangle() {
int x=1,triangleNumber=1;
while(triangleNumber<num){
x++;
triangleNumber = triangleNumber + x;
}
if(triangleNumber==num)
{
System.out.println(num+" is a triangle number");
}
else
{
System.out.println(num+" is applicable for both triangle and square numbers");
}
}
}
}
Number mynum = new Number();
mynum.num=2;
System.out.println(mynum.isSquare());
}
}
So first it would be much easier for you to just do this:
public boolean isSquare(int num){
...
}
And so get rid of:
mynum.num = yourNumber;
As very often you will encounter this approach in methods, where the raw input is can be any number/text...
Now for your code, a very good optimization is:
public boolean isSquare(int num){
if (num>0) //To check if the number is null or not...
squareNumber = num*num;
}
Because the while loop condition is always met once and then exited after the first entry...
Moving on to the next part... which for me, is very tricky as I see it useless because it always returns true (the text) as the "squareNumber" always has num as root, and will always pass if (squareNumber%num==0) as true, and isTriangle(...) will never be called.
The more approachable way is:
public class HelloWorld {
static String result;
public static void main(String[] args) {
int mynum = 36;
System.out.print(isSquare(mynum)+isTriangle(mynum));
}
public static String isSquare(int num){
if ((Math.sqrt(num)==(int)Math.sqrt(num))){
return "Given number is a square";
} else return "Given number isn't a square,";
}
public static String isTriangle(int num){
if (isSquare(8*num+1)){
return " but is still a triangular number!";
} else return " but not a triangular number.";
}
}
public static void main(String []args){
class Number{
int num;
public boolean isSquare(){
int squareNumber=1;
while(squareNumber<num){
squareNumber = num*num;
}
if(squareNumber%num==0)
{
System.out.println(num+" is a Square number");
}
return isTriangle();
}
boolean isTriangle() {
int x=1,triangleNumber=1;
while(triangleNumber<num){
x++;
triangleNumber = triangleNumber + x;
}
if(triangleNumber==num)
{
System.out.println(num+" is a triangle number");
return true;
}
else
{
System.out.println(num+" is applicable for both triangle and square numbers");
}
return false;
}
}
Number mynum = new Number();
mynum.num=2;
System.out.println(mynum.isSquare());
}
I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;
I have a program (written in Java) that when it reaches a for or a while loop, it stalls for about 2 seconds then stops completely. Here is the code:
import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct=false)
for(x=0;x>999999999;x++)
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}
You can see that I have comments for the while loop stuff. Also, I have put in 4 println statements where I thought it would be getting stuck, and it printed 1 and 2, but not 3. Here is the portion of my cleanUsage class that contains the random number generator:
public static int random(int min, int max)
{
int range = max - min + 1;
int number = (int) (range * Math.random() + min);
return number;
}
I have asked some other people and they could not figure it out. If you could help me out, that would be great.
It doesn't print 3 or 4 because the condition x>999999999 is initially false so that for loop is never entered. I assume you meant <.
Also note that you can use break rather than correct = true to exit a loop.
import javax.swing.*;
public class numberCruncher
{
public static int number,guess,x;
public static void main(String[] argv)
{
number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):");
System.out.print("1");
test();
}
public static void test()
{
boolean correct = false;
System.out.print("2");
//while(correct==false) // equality test, not assignment
for(x=0;x<999999999;x++) //2nd argument is continue while false
{
//x++;
System.out.print("3");
guess=cleanUsage.random(0,99999);
System.out.print("4");
System.out.println(" "+guess);
if (guess==number)
{
System.out.println();
System.out.println("Correct number guessed in "+x+" tries");
//correct = true;
}
}
}
public static int enterIntGUI(String prompt)
{
String tempString = JOptionPane.showInputDialog(prompt);
int temp = Integer.parseInt(tempString);
return temp;
}
}
i keep getting a ';' is expected at the checkBinary(String num) { ^ error, yet i can't find any place for a ";". I have only been studying java for a few days so the problem could be something obvious i haven't learnt yet. Please provide a detailed explanation in way i could use it to prevent the problem in later projects. Thank you in advance!
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
}
You need to move your checkBinary method outside of the main method. You cannot nest methods in java without declaring an inner class.
This should work:
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
}
}
If you want to know how to go about solving this with a nested class, there are numerous other questions/examples on SO. Like this one Can methods in java be nested and what is the effect? or In java what are nested classes and what do they do?
I am creating a Guessing game program in java code. I am having an issue with the main class and the tester class running. Any help would be appreciated. The instructions for the game are The computer generates a random # and the user must guess that number in 7 or fewer guesses. If the guesses exceed 7, then the game is over and the user is asked if they want to 'play again?'
Here is my guess class:
import java.util.Random;
public class Guess
{
int computersNumber; // A random number picked by the computer.
int usersGuess = 0; // A number entered by user as a guess.
int guessCount = 0; // Number of guesses the user has made.
Random random = new Random();
int randomNumber = random.nextInt(100);
public Guess(int n)
{
usersGuess = n;
}
public boolean getGuess()
{
boolean isValid = false;
if (isValid)
{
return false;
}
if (usersGuess == computersNumber)
{
return true;
}
return isValid;
}
public boolean isGuessCorrect()
{
return getGuess() == computersNumber;
}
public int getCount()
{
guessCount ++;
return guessCount;
}
boolean playAgain;
}
Tester/main class:
import java.util.Scanner;
public class GuessTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Let's play a game!");
System.out.println();
System.out.println("The computer will generate a number between 0 and 100. You will have up to seven guesses"
+ "to figure out what the number is. Good luck!");
System.out.println();
System.out.print("What is your first guess? ");
int n = in.nextInt();
Guess guess = new Guess(n);
if (guess.getGuess == computersNumber)
{
System.out.println("That's Correct! ");
}
if (getCount == 7)
{
System.out.println("You lose, you didn't get the number in 7 guesses.");
}
System.out.println("Would you like to play again? ");
in.nextBoolean();
System.out.println();
System.out.println("Thanks for playing.");
in.close();
}
}
There are a few things in your code that don't compile. Did you post all your code?
First things first: if you have a class Guess and you want to access its methods, you need to instantiate an Object of that class first:
int n = in.nextInt();
Guess guess = new Guess(n);
Next, in order to actually access a method of guess it is written like this:
if (guess.getGuess() == computersNumber) {
System.out.println("That's Correct! ");
}
However in your example, the variable computersNumber is not defined in the main class but it is a member of the Guess class. Since both the computersNumber and the method getGuess() are part of the Guess class it would be better to actually access them from within that class and do the comparison there. Maybe in a separate method:
public class Guess{
....
public boolean isGuessCorrect(){
return getGuess() == computersNumber;
}
}
Another thing I saw in your Guess class is that you access some boolean variable in getGuess(), which is not defined:
if (!isValid) {
return false;
}
Where does isValid come from? where is it defined?
Edit: a little hint for the road:
You can generate a random number between 0 and 100 like this:
Random random = new Random();
int randomNumber = random.nextInt(100); // this will be a number between 0 and 100
int another = random.nextInt(1000); // you can reuse the random object and generate more numbers