Logical Error in Java Program - java

I have created two methods that take in a number and should count from that number to 0 and print it out. One method incorporates a while loop, which works fine. The other method uses a for loop. But for some reason, I'm not getting the expected output in the method that uses a for loop. How come?
import java.util.*;
public class Methods
{
public static void main(String[] args)
{
int n = 10;
countdown(n);
countdown2(n);
}
public static int countdown(int num)
{
while(num >= 0)
{
System.out.println(num);
num--;
}
return 0;
}
public static int countdown2(int number)
{
for(int i = number; i <= number; i--)
{
System.out.println(number);
number--;
}
return 0;
}
}

Because of the way you've structured the for loop conditions:
i is initially set to the same value as number.
The loop continues while i is less than or equal to number.
i gets decremented every time round the loop.
Since i starts out as less than or equal to number, and gets smaller, you're not going to exit the loop any time soon. (This will only happen when i gets down to Integer.MIN_VALUE and then underflows to Integer.MAX_VALUE on the next iteration).
Changing the condition to i > 0 would be one way of resolving this; or you could initially set i to zero and increment it each time round the loop.

for(int i = number; i <= number; i--)
check loop your count is starting from number to number only.
you should count from number to 0.
for(int i = number; i >= 0; i--)

If ever a program is behaving in a way which does make sense, the first thing you should try is use the debugger to debug your code. This allows you to step through the program line by line and see what all the values are
If you have a while loop you can exchange it with a for loop like so (provide you don't have a continue statement)
for({initialise variable};{condition};{update expression}) {
{do something}
}
with
{initialise variable}
while({condition}) {
{do something}
{update expression}
}
or
{initialise variable}
while(true) {
if ({condition}) break;
{do something}
{update expression}
}
or
{initialise variable}
if({condition})
do {
{do something}
{update expression}
} while({condition});

public static int countdown2(int number)
{
for(;number>=0;)
{
System.out.println(number);
number--;
}
return 0;
}

That should work
public static int countdown2(int number)
{
for(int i = number; i >= 0; i--)
{
System.out.println(number);
number--;
}
return 0;
}

The condition in the second loop should be
i >= 0

public static int countdown2(int number)
{
for(int i = number; i >= 0; i--)
{
System.out.println(number);
number--;
}
return 0;
}

Related

Java function is not returning expected value

A bug in a program I'm writing as an assignment for my java.
Objective: program should take two parameters and find all the odd numbers between those parameters. Then it should return the sum of all those numbers.
Bug: When the parameters are negative or starting number is greater than the ending number, it should return -1. But my program is returning 0.
Maybe my program isn't updating the sum value inside the loop. But even so, as per return condition, my function should return -1, not the sum.
public class SumOddRange{
public static void main(String[] args){
System.out.println(sumOdd(10,5));
}
public static boolean isOdd(int number){
return (number<0)||(number%2==0)?false:true;
}
public static int sumOdd(int start, int end){
int sum = 0;
for(int i=start; i<=end; i++){
if(isOdd(i)){
sum+=i;
}
}
return (start<=0)&&(start>end)? -1: sum;
}
}
Put the input check as the first thing in your method and change the && to an || since you want to return if the first check fails or the second check fails, not only if both fail. And the isOdd can be inlined:
public static int sumOdd(int start, int end){
if (start <= 0 || start > end)
return -1;
int sum = 0;
for (int i = start; i <= end; i++) {
if (i % 2 != 0) { // or if (i % 2 == 1) {
sum += i;
}
}
return sum;
}
There is a logic error in your line return (start<=0)&&(start>end)? -1: sum;
You have to return -1 if start is <0 or start > end, so use "||" (logical Or) instead of "&&" (logical and):
return (start<=0)||(start>end)? -1: sum;
Please go through #luk2302's answer for a better solution.

Using IsPrime method in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is my code to use IsPrime method to determine total number of primes between 0 and 1000 and print the total number of primes at last. Can anyone tell what's wrong with the code.
public static void main(String[] args) {
int z=0;
// z is the variable that holds total number of primes
//n is divisor
//i is dividend
if (isPrime(i)) {
z++;
}
System.out.print(z+"\n");
}
public static boolean isPrime(int n){
{
for(i=0; i<1000; i++)
{
for(n=0; n<i; n++)
if(i%n==0)
return false;
else
return true;
}
}
}
Thanks in advance
Formatting it might help you discover the error.
I see a few things that's wrong with your code:
From what I can see, you have an extra open curly bracket in your isPrime method.
i isn't declared in your main method.
You need to wrap your if(isPrime(i)) statement inside a for loop that goes from 0 to 1000. Like the following:
for (int i = 0; i <= 1000; i++) {
if (isPrime(i))
z++;
}
That way, it will be actually checking all the prime numbers from 0 to 1000
For good coding practices, I would name your z variable to be something like counter so that it's clear what that variable is supposed to be doing. i in for-loop is okay since that's a common way to index through the loop.
You can also use several tactics to optimize your code. You can use Math.sqrt() function, as well as start your for loop from 3 and go up by increment of 2 (since any even number will be dividable by 2) and initialize your counter from 1 since 2 will already be a prime number.
public static boolean isPrime(int n){
int factors = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0) // ensure that you mod n not i
factors++;
}
// if factors count is equals to 2 then it is prime number else it's not prime number
if(factors == 2)
return true;
else
return false;
}
Check this modified code once for your reference.
I think you had a few things turned around.
Why not loop from 1 to 1000 in your primary function and then use the isPrime function to determine if each number is prime.
In the isPrime function, you count from 2 to 1/2 the value of the number and do the divisions to determine if it is prime. Return False if it is divisible.
public static void main(String[] args) {
int z=0;
for (i=1;i<=1000;i++) {
if (isPrime(i))
{
z++;
}
}
System.out.print(z+"\n");
}
public static boolean isPrime(int n){
for(i=2; i<=n/2; i++)
{
if(n%i==0) return false;
}
return true;
}
This will count the number of primes based on this link and your original answer...
public static void main(String[] args) {
int isPrimeCount = 0;
for(i=0; i<1000; i++)
{
if(Check_Prime(i))
{
isPrimeCount++;
}
System.out.println(isPrimeCount);
}
}
private static boolean Check_Prime(int number) {
int i;
for (i = 2; i <= number - 1; i++)
{
if (number % i == 0)
{
return false;
}
}
if (i == number)
{
return true;
}
return false;
}
You need to define the variable "i" before you pass it to the isPrime() method in main(). It seems as though whoever wrote the code did not fully understand what a prime number was. According to wikipedia "A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. " With this in mind you need to make sure that the value you pass to the isPrime() method is greater than 1. After look at your code I made some changes. I made the isPrime() method return false if the input value is <=1. Also, I made the isPrime() method return true if the input value is 2. I made other changes in the code that would make the for statement operate n-1 times because that is all that is needed to find out if the number is prime because all numbers are divisible by themselves. Also the for statement starts at the value 2. Your if-then-else return statements within the for loop is illogical because it will return a value without going through the entire loop. You did not need the inner for loop.
Here's a link on prime numbers
Here is the new code:
public class AreaComparison {
/**
* Starts the program.
*
* #param command line arguments
*/
public static void main(String[] args) {
int z = 0;
int i = 2;
// z is the variable that holds total number of primes
//n is divisor
//i is dividend
if (isPrime(i)) {
z++;
}
System.out.print(z + "\n");
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if(n == 2){
return true;
}
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Java program. How do I loop my "isLucky" method through my array? Also, how do I print my results correctly in the main method?

First off, my program is not compiling. Any ideas? I have no idea why and my Eclipse program isn't working...
Also, how do I get my "isLucky" method to loop through my array?
And did I print out my results correctly in the main method?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
System.out.println(sum(a))
else
result = sumOfEvens(a);
System.out.println(sumOfEvens(a))
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false;
}
// write the static methods isLucky, sum, and sumOfEvens
}
Your compiler error, 'else' without 'if' is because you have something like this:
if(isOkay)
doSomething();
andThenDoSomethingElse();
else
doAnotherThing();
andEvenSomethingElse();
And you must put each block in curly braces, like this:
if(isOkay) {
doSomething();
andThenDoSomethingElse();
} else {
doAnotherThing();
andEvenSomethingElse();
}
I strongly recommend using curly braces in all ifs (and whiles and fors and everything else), even when there's only a single statement.
More information can be found at this question: Else without if
Honestly there is no regulation that says we have to use code blocks. Syntax typically says that after we read the if we are looking for only one statement if your condition contains multiple statements then we do have to block that code up, another thing is try to keep that indentation whenever you enter methods conditions and then statements. Id love to write the easy route to get the output you desire. Think about this why are you sending these methods arrays? What is stopping you from simply looping in your main method and passing each iteration to these methods sum lucky, even...Your variables should usually be initialized at top or at the beginning of a method to have those around the life of a methods execution.Below is clearly not compile ready code, however this will edge you in the right place to understand this problem more than use brackets.
boolean isLucky;
int[] IntegerArray;
Scanner scan;
//Final for constant values Typically these would be in all uppercase to indicate to
//other that this is a final anywhere
//in this class those will stick out.
final int luckyOne = 7;
final int luckyTwo = 13;
final int luckyThree = 18;
for(int i=0;i<IntegerArray.length;i++){
//snag me Boolean value for this number
isLucky();
if(isLucky)//example of completely legal if statement adding a system.out statement
//means yes i have to block this
sum(i);
else
even(i);
}

Statements outside for loop are not being executed

I'm new to Java. I found a website called project eulder and was practicing on a problem.
I don't understand why the following program does not display anything but when I put System.out.println(max); into the for loop it works but displaying all the prime numbers including the biggest. Who do I only the display the biggest prime number?
public class LargestPrimeFactor {
public static void main(String[] args) {
long x = 600851475143L;
int max = 0;
for (int i = 1; i <= x; i++) {
if (x % i == 0)
if (isPrime(i))
max = i;
}
System.out.println(max);
}
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
You have written an infinite loop: 600851475143L is greater than the maximum value that can be stored in an int, so i <= x will always be true.
Changing i and all the other relevant variables to long may solve this issue, but you'll still have to rethink your algorithm. Checking if 600851475143 numbers are prime is just going to take too long.
Hint: once you have found a number that divides x, you can divide x by that number... (Hope this doesn't spoil the fun)

Prime Tester for speed

I was given a homework assignment in Java to create classes that find Prime number and etc (you will see in code better).
My code:
class Primes {
public static boolean IsPrime(long num) {
if (num%2==0){
return false;
}
for (int i=3; i*i<=num;i+=2) {
if (num%i==0) {
return false;
}
}
return true;
} // End boolen IsPrime
public static int[] primes(int min, int max){
int counter=0;
int arcount=0;
for (int i=min;i<max;i++){
if (IsPrime(i)){
counter++;
}
}
int [] arr= new int[counter];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arr[arcount]=i;
arcount++;
}
}
return arr;
} // End Primes
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(long num){
long e = 0 , d = 0 , f = num;
for (int i = 2; i <= num + 1 ; i++){
if ((num + 1) % i == 0){
if ((num + 1) % i == 0 && (num + 1) == i){
d = num + 1;
break;
}
num++;
i = 1;
}
}
num = f;
for (int i = 2; i < num; i++){
if ((num - 1) % i == 0){
if ((num - 1) % i == 0 && (num - 1) == i){
e = num - 1;
break;
}
num--;
i = 1;
}
}
num = f;
if (d - num < num - e) System.out.println("Closest Prime: "+d);
else System.out.println("Closest Prime: "+e);
return (int) num;
} // End closestPrime
}//end class
The goal of my code is to be faster (and correct). I'm having difficulties achieving this. Suggestions?
**New code:
class Primes {
public static boolean IsPrime(int num) {
if (num==1){
return false;
}
for (int i=2; i<Math.sqrt(num);i++) {
if (num%i==0) {
return false;
}
}
return true;
}
// End boolen IsPrime
public static int[] primes(int min, int max){
int size=0;
int [] arrtemp= new int[max-min];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arrtemp[size]=i;
size++;
}
}
int [] arr= new int[size];
for (int i=0;i<size;i++){
arr[i]=arrtemp[i];
}
return arr;
}
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(int num) {
int count=1;
for (int i=num;;i++){
int plus=num+count, minus=num-count;
if (IsPrime(minus)){
return minus;
}
if (IsPrime(plus)) {
return plus;
}
count=count+1;
}
} // End closestPrime
}//end class
I did try to make it a bit better. what do you think, it can be improved more? (the speed test is still high...)
In your primes function you:
Check if the current number is divisible by two
Check to see if it's prime
Create an array to put your output in.
Check every number in the range again for primality before putting it in your array.
The problem is in the last step. By double-checking whether each number is prime, you're duplicating your most expensive operations.
You could use a dynamic data structure and add prime numbers to it as you find them. That way you only need to check once.
Alternatively, you could create a boolean array which is the size of your input range. Then as you find primes, set the corresponding array value to true.
UPDATE:
There are still a number of improvements you can make, but some will require more work than others to implement. Look at the specifics of your test and see what fits your needs.
Low-hanging fruit:
Use an ArrayList to collect primes as you find them in primes, as opposed to looping over the values twice.
In closestPrime, you're checking every single value on either side of num: half of these are even, thus not prime. You could adapt your code to check only odd numbers for primality.
Trickier to implement:
Try a more advanced algorithm for IsPrime: check out the Sieve of Eratosthenes
Above all, you should spend some time figuring out exactly where the bottlenecks are in your code. Oftentimes performance problems are caused by code we thought was perfectly fine. You might consider looking into the code-profiling options available in your development environment.
You make quite a few calls to isPrime(), each of which is very expensive. Your first step should be to minimize the number of times you do that, since the result doesn't change for any given number, there's no point calling more than once. You can do this with memoization by storing the values once they're computed:
ArrayList<Integer> memoList = new ArrayList<Integer>();
for(int i = 0; i < max; i++) {
if(isPrime(i)) {
memoList.add(i);
}
}
Now memoList holds all the primes you need, up to max, and you can loop over them rapidly without needing to recompute them every time.
Secondly, you can improve your isPrime() method. Your solution loops over every odd number from 3 to sqrt(n), but why not just loop over the primes, now that we know them?
public static boolean IsPrime(long num) {
for(int p : memoList) {
if(num % p == 0) {
return false;
}
}
return true;
}
These changes should dramatically improve how quickly your code runs, but there has been a lot of research into even more efficient ways of calculating primes. The Wikipedia page on Prime Numbers has some very good information on further tactics (prime sieves, in particular) you can experiment with.
Remember that as this is homework you should be sure to cite this page when you turn it in. You're welcome to use and expand upon this code, but not citing this question and any other resources you use is plagiarism.
I see a couple problems with your answer. First, 2 is a prime number. Your first conditional in IsPrime breaks this. Second, in your primes method, you are cycling through all number from min to max. You can safely ignore all negative numbers and all even numbers (as you do in IsPrime). It would make more sense to combine these two methods and save all the extra cycles.

Categories