Prime Number test beginner Java - java

College assignment for testing a positive number (called num) is a Prime Number or not.
I must use a Do while loop
Ive attempted the code as follows but its failing the test
public class Primes {
public static main void (String args[]){
int num = 1;
int 2 = 0;
boolean flag = false;
do {
if (num%i == 1) {
flag = true;
break:
}
num ++
while (i<=num);
{
if (flag = true);
{
System.out.println (num + "is a prime number ");
}
else
{
System.out.prinln (num + "is not a prime number ");
}
}
}
}

1. Main function signature
it should be
public static void main(String args[])
not
public static main void (String args[])
2. you cannot start a variable name with a number
int 2 = 0;
you probably mean
int i = 0;
3. do { ... } while(...);
The format of a do while loop is
do {
something();
} while (condition);
4. Semicolon means end of statement
while (condition); {
something();
}
in this case something() is not in your while loop
5. Watch out for assignment in if
if (flag = true)
this is assigning flag to true. And the condition is always true (since the resulting of the assignment is true).
6. Not System.out.prinln
It is System.out.println. Use an IDE.
Final solution
public class Primes {
public static void main(String args[]) {
int num = 3;
int i = 2;
boolean flag = false;
do {
if (num % i == 0) {
flag = true;
break;
}
i++;
} while (i < num);
if (!flag) {
System.out.println(num + " is a prime number ");
} else {
System.out.println(num + " is not a prime number ");
}
}
}
I also fixed some logical problem such as
you should probably increment i instead of num,
while (i < num) instead of while (i<=num), otherwise some (last) i always equals to num, making everything not a prime
a number is not a prime when flag is true. you should probably invert the if logic. Flag is true when you find something that is evenly divisible, meaning the number is not a prime.
There are better solutions, but I stick with your format.

You have a couple of different issues:
Firstly, it should be:
public static void main(String[] args){
Second, your variable on line 4 doesn't have name.
Your format for your do while statement is also, not quite right.
Another poster has a good example of a do while loop here:
Do-while loop java explanation
Also, go over the rules for where semicolons should be placed.

Related

How to print another term at the end after the loop? In java

import java.util.Scanner;
public class PrimeNumbers {
public static boolean prime(int num) {
boolean flag = true;
for(int i=2;i<=num/2;i++) {
if(num%i==0) {
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
String separator = "";
Scanner scan = new Scanner(System.in);
System.out.println("First num:");
int low = scan.nextInt();
System.out.println("Second num:");
int high = scan.nextInt();
if(low>high||high<=0||low<0||(high-low) == 1) {
System.out.println("Invalid input");
System.exit(0);
}
while(low<high) {
if(prime(low)==true) {
System.out.printf(separator+"%d",low);
separator = ",";
}
low++;
}
}
}
Example:
first num:1
second num:10
Output: 1,2,3,5,7
My requirement is,I need to check the 'second num' input if its prime or not, and if it is not prime, print the next prime number.
Example:
first num:1
second num:
Output: 1,2,3,5,7,11
int lastNumber = high;
if(!prime(lastNumber))
{
while(!prime(++lastNumber));
// now you have to prime number after the high or that number itself if it
//is the prime
}
// now print all numbers and lastNumber in the last
You did num/2 if the first loop which is good for performance but you can increase
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10
checks

a prime number program that allows the user to test numbers till the user enters zero. However, after testing 6 numbers, it prints incorrect message

a prime number program that allows the user to test whether a number is prime or not till the user enters zero. However, after testing about 6 numbers, it prints incorrect message like it prints the number is a prime for a non-prime number also and prints a number is not a prime number for prime numbers.
package com.selfexercise.exercise;
/**
* Created by One on 2/15/2017.
*/
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
int n;
boolean flag=true;
Scanner in = new Scanner(System.in);
for(;;) {
System.out.print("\nPlease enter a number : ");
n = in.nextInt();
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = false;
break;
}
}
if (flag) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
if(n==0)
break;
}
}
}
You declare flag = true at the start of your program. Then, as soon as you find a factor, it gets set to false, so you know the number is not prime.
But then, when another number is input by the user, flag is already false. You need to set it to true each time you get a new number from the user.
// no need to declare flag before the loop
for(;;) {
// initialise flag to true for each input number
boolean flag = true;
System.out.print("\nPlease enter a number : ");
n = in.nextInt();
...
Others have pointed out your error. I have a couple of other comments on your code.
First, your prime checking system works, but is inefficient. The Sieve of Eratosthenes is much faster than Trial Division, the method you are using. Even with just trial division your code can be made faster by using a limit of sqrt(n) in place of n / 2 and treating even numbers separately. It is also traditional to keep the main code cleaner by putting prime checking into a separate boolean method:
boolean isPrime(int num) {
// Low and negative numbers.
if (num < 2) {
return false;
}
// Even numbers.
if (num % 2 == 0) {
// Two is the only even prime.
return num == 2;
}
// Odd numbers.
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
} // end isPrime()
That method can be reused whenever you need to check for prime numbers.
Second, your handling of the loop in your main code seems clumsy, such as using a break to exit. Given that you are repeatedly reading input from your user until a 0 is entered, then a do ... while loop fits best:
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
do {
System.out.print("\nPlease enter a number or 0 to quit : ");
n = in.nextInt();
if (isPrime(n)) {
System.out.println(n + " is a prime number.");
} else {
System.out.println(n + " is not a prime number.");
}
} while (n != 0);
}
This uses the isPrime() method from earlier, which replaces your flag variable. Notice that using a do ... while loop eliminates the explicit break from the loop. That is because that style of loop is a better fit for what you are doing than the for loop you used earlier. The for loop would be better if you knew in advance how many numbers you were going to have to test.
if (flag) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
flag = true;
Hopefully that would help? Once the variable flag becomes false, your code allows no instruction to reset it back to default state for the next iterations inside for(;;) loop

Program wont compile and has a missing return statement error

I can't seem to get my code to compile. Everytime I try, there is an error at the }(closing bracket) saying missing return statement.
import java.util.Scanner
public class Fibonacci
{
public static int fibonacciNumber( int n)
{
while(n != 00)
{
if( n == 0)
{
return 0;
}
else if(n == 1)
{
return 1;
}
else if(n > 1)
{
return fibonacciNumber(n-1) + fibonacciNumber(n-2);
}
}
}
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to calculate(enter 00 to quit): ");
int n = in.nextInt();
System.out.println( fibonacciNumber( n));
}
}
Because you're missing a return statement. Consider your method:
public static int fibonacciNumber( int n)
{
while(n != 00)
{
// some logic that returns something
}
}
What happens if n does equal 00? Nothing is returned. The compiler is ensuring that every logical path for a method returns a value. So after your while loop you need to return a value, in case that loop was never entered.
Or, for that matter, what happens if n is less than 0? None of your current return statements would be reached and, in fact, you'd have an infinite loop.
Basically, if your method declares that it returns a value, then it must return a value. Currently you're not guaranteeing that, hence the compiler error.
well of course it's asking for a return statement.
public static int fibonacciNumber( int n)
your function needs to return an integer, but you aren't returning anything because you have a lot of if's with nested returns.
else if(n > 1)
{
return fibonacciNumber(n-1) + fibonacciNumber(n-2);
}
//HERE SHOULD YOUR RETURN BE, outside of the while loop
It seems as if you try to develop an application that prints the n-th fibonnaci-Number until the user decides to quit the application. But for that goal, your while-loop is located in the wrong location. It should be located in the main containing the reading of the user input and computation of the fibonnaci-number. Then it becomes clear, that you are missing a return, since the fibonacci-method has four possible alternatives:
1. n==0
2. n==1
3. n>1
4. all else (which is n<0)
You now have the possibility to either return some value for the negative n case, throw an Exception or merge it with the n>1 case.
The latter would be looking something like this:
import java.util.Scanner;
public class Fibonacci {
public static int fibonacciNumber( int n) {
if(n == 0) {
return 0;
} else if(n == 1) {
return 1;
}
return fibonacciNumber(n-1) + fibonacciNumber(n-2);
}
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to calculate(enter 00 to quit): ");
int n = in.nextInt();
while(n != 0) {
System.out.println( fibonacciNumber( n));
in.nextLine(); // Just to parse the line-separator
n = in.nextInt();
}
}
}
The in.nextLine() is required since you type the number into the console but submit it via the enter-key. That results in the Line-Break-Character being read the next time you call in.nextXXX() which would result in an Exception. Also, since you use in.nextInt() if you type 00 it is parsed to an integer with the value of 0. Therefore it is not exactly correct to tell the user to type 00 to quit the application.

Homework Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Objective:
(Palindrome integer) Write the methods with the following headers:
// Return the reversal of an integer, i.e., reverse(456) returns 654
public static int reverse(int number)
// Return true if number is a palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome
if its reversal is the same as itself. Write a test program that prompts the
user to enter an integer and reports whether the integer is a palindrome.
My code is below... My attempt is below. I've collapsed and I don't know what else to do BUT come here. I'm stuck on the Boolean portion of the code and do not know if the rest of this code is right. I've scoured the internet and seen very few examples but none of them made any sense. I'm a visual learner, so none of this really makes sense to me. Started Java 2 months ago so please don't expect me to produce gold with extremely limited knowledge. I need help-help, not petty or witty comments. If you don't want to offer help, don't comment.
public class NewClass {
public static int reverse(int number) {
int remainder = 0;
while (number != 0) {
remainder = number % 10;
number = number / 10;
System.out.print(remainder);
}
System.out.println(" is the reverse number.");
return remainder;
}
//I don't really know what to do here.
public static boolean isPalindrome(int number, int remainder) {
return number == remainder;
}
//Nor do I know what I'm doing here. I'm supposed to make the result from 'reverse' either true or false but I don't know what it write, considering the 'Boolean' portion is unfinished.
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
int remainder = 0;
if ( remainder == ture)
}
}
Revised:
public class NewClass {
public static int reverse(int number) {
int reverse = 0;
while (number != 0) {
reverse = (reverse * 10) + number % 10;
number = number / 10;
System.out.print(reverse);
}
System.out.println(" is the reverse number.");
return (reverse);
}
public static boolean isPalindrome(int number) {
return (number == reverse(number)); //Still being asked to introduce this line. I don't know what that means. My book says nothing and the internets isn't helping.
}
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
if (number == reverse(number)) {
System.out.println(number + " is a palindrome");
}
else{
System.out.println(number + " is not a palindrome");
}
}
}
**Results:
run:
Enter an integer: 121
112121 is the reverse number.
112121 is the reverse number.
121 is a palindrome
BUILD SUCCESSFUL (total time: 2 seconds)**
My question: I don't know what I'm doing with the true and false portion of this code. The point is to check the number, compare it to the reversed number checking whether it is a palindrome or not. The second issue is with the reverse number repeating itself with double the number... I don't know what I'm doing wrong or how to fix it.
Query:
public static boolean isPalindrome(int number) {
return (number == reverse(number));
}
I'm being asked to introduce this line but I don't know what it means. It's the only error I have. It's supposed to return the true or false, correct? What do I do with it because it seems like I created a code that doesn't need that specific line, even though it is required.
If you're talking about how to implement isPalindrome in terms of reverse, it's simply figuring out if the number and its reverse are the same.
So, for example, 767 is a palindrome because, when reversed, it's equal to the original. However, 314159 is not a palindrome because its reversal is a totally different number, 951413.
That means pseudo-code like this should suffice (I've included reverse because your current implementation, while close, returns the final remainder rather than the reversed number):
def reverse(num):
rnum = 0
while num != 0:
rnum = (rnum * 10) + (num % 10)
num = num / 10
return rnum
def isPalindrome(num):
return (num == reverse(num))
If you want to nut it out yourself, don't look below. This is how I'd approach it for this level of skill and I'm providing it just for completeness.
public class Test {
public static int reverse (int num) {
int rnum = 0;
while (num > 0) {
rnum = (rnum * 10) + (num % 10);
num = num / 10;
}
return rnum;
}
public static boolean isPalindrome (int num) {
return (num == reverse (num));
}
public static void main(String args[])
{
System.out.println(isPalindrome (767));
System.out.println(isPalindrome (12321));
System.out.println(isPalindrome (4));
System.out.println(isPalindrome (314159));
}
}
I personally use my two methods for doing it, but the guy who did the StringBuilder thing did good too :).
Here is my code for reversal and then I call that and check if it a palindrome.
public static String reverseString(String str)
{
String blank = "";
for(int i = str.length()-1; i >= 0; i--)
{
blank = blank + str.charAt(i);
}
return blank;
}
// NOW you can call isPalindrome("Whatever string you wanna check.");
public static boolean isPalindrome(String str)
{
String reverse = reverseString(str);
if(str.equalsIgnoreCase(reverse))
{
return true;
}
else
{
return false;
}
}
Here is example for check the given number is palindrome or not .
public static void main(String [] args) {
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Java method to check if number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}

Determine whether number is odd or even without using conditional code

How to find whether a number is odd or even, without using if condition or ternary operators in Java?
This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.
There are few ways to not use if and get behavior that will be same as if if was used, like ternary operator condition ? valueIfTrue : valueIfFalse or switch/case.
But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like
int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
output:
13 is odd
You can change number % 2 with number & 1 to use suggestion of your teacher. Explanation of how it works can be found here.
Consider a number's representation in binary format (E.g., 5 would be 0b101).
An odd number has a "1" as its singles digit, an even number had a zero there. So all you have to do is bitwise-and it with 1 to extract only that digit, and examine the result:
public static boolean isEven (int num) {
return (num & 1) == 0;
}
int isOdd = (number & 1);
isOdd will be 1 if number is odd, otherwise it will be 0.
Did you mean something like this?
boolean isEven(int value) {
return value % 2 == 0;
}
boolean isOdd(int value) {
return value % 2 == 1;
}
Every odd number have 1 at the end of its binary representation.
Sample :
public static boolean isEven(int num) {
return (num & 1) == 0;
}
Just saw now 'Without using IF'
boolean isEven(double num) { return (num % 2 == 0) }
Just a quick wrapper over the already defined process...
public String OddEven(int n){
String oe[] = new String[]{"even","odd"};
return oe[n & 1];
}
I would use:
( (x%2)==0 ? return "x is even" : return "x is odd");
One line code.
Method 1:
System.out.println(new String[]{"even","odd"}[Math.abs(n%2)]);
Method 2:
System.out.println(new String[]{"odd","even"}[(n|1)-n]);
Method 1 differs from the accepted answer in the way that it accounts for negative numbers as well, which are also considered for even/odd.
import java.util.Scanner;
public class EvenOddExample
{
public static void main(String[] args)
{
System.out.println("\nEnter any Number To check Even or Odd");
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
int no1=no;
while (no>1)
{
no=no-2;
}
if(no==0)
{
System.out.println(no1 +" is evenNumber");
}
else
{
System.out.println(no1 +" is odd Number");
}
}
}
you can also use bitwise shift operators
(number >> 1)<<1 == number then even else odd
# /* **this program find number is odd or even without using if-else,
## switch-case, neither any java library function...*/
##//find odd and even number without using any condition
class OddEven {
public static void main(String[] args) {
int number = 14;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
}
}
/**************OUTPUT*************
// 14 is even
// ...................
//13 is odd

Categories

Resources