what i'm i doing wrong on this algorithm? - java

I've been stuck on this code for a couple of hours.
The sum is S = 1-x + x^2 - x^3 + x^4.
We ask for X and N with starting value of i = 0.
Whenever the previous exponent (i) is odd we add x^i, and
if the previous exponent is even we subtract x^i.
I've put them on a loop but i can't seem to get the sum correctly.
Can anyone tell me what I'm doing wrong?
Thank you!
import java.util.Scanner;
public class hw1 {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int X = scan.nextInt();
System.out.println("Enter number N");
int N = scan.nextInt();
int sum = 0;
for (int i = 0; i <= N; i++) {
if (i < N) {
if (i % 2 != 0) // if I is even
{
sum = sum - (X ^ i);
} else // if I is odd
{
sum = sum + (X ^ i);
}
}
}
System.out.println("Z is " + sum);
}
}
}

So I fixed a few things in your code:
I switched the ^ operator (which, as #Nick Bell pointed out, is a bitwise exclusive OR) for Math.pow.
I fixed the spelling of your variables x and n. In Java, convention is to give variables names that start with lower-case. Upper-cases (X and N) are reserved for constants (fields marked final) and for classes (as opposed to objects). Note that this is only a convention, and that the code works fine both ways. It just helps in reading the code.
Your odd/even check was inverted: x % 2 == 0 is true for even numbers.
The reason that you inverted your odd/even check was probably the two operations on sum were inverted. Compare with the description of your problem in the first paragraph of your question, you'll see where you went wrong.
The if i < N check was redundant. It you really wanted to limit computation to i < N, you should specify it directly in your first for loop.
I added two try/catch blocks with infinite loops that break when an integer is entered, because your previous code threw an exception and stopped if you entered something else than a well-formed integer (such as letters, or a decimal value). Up to you to keep them or delete them.
By the way, initializing x and n to 0 is now redundant, since your code is guaranteed to assign them another value right away.
This is the updated code.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int x = 0;
while (true) {
try {
x = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
System.out.println("Enter number N");
int n = 0;
while (true) {
try {
n = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
double sum = 0;
for (int i = 0; i <= n; i++) {
if (i % 2 == 0) // if I is even
sum = sum + Math.pow(x, i);
else // if I is odd
sum = sum - Math.pow(x, i);
}
System.out.println("Z is " + sum);
}
}

Related

Explain if block nesting

This is regarding some homework and I tried to make a range which is 10 to 40.
The code would accept two inputs within the range. The method will then check if both numbers are within the range and then if they are it would give me the product of both numbers, if not it is suppose to show me a message.
I have been working on this for quite a long time and I cant get it to work I am a complete beginner.
public class testing
{
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
int total = first * second;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
total = first * second;
} else {
System.out.println("Number is not in range, please try again");
}
}
}
}
return total;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
System.out.print("Product of x and y = " + total);
}
}
Expected result is to show me if the numbers are not in range but it is not doing so currently.
It gives me the product of both numbers regardless whether it is in the range.
Here:
int total = first * second;
followed by an if, follewed by:
return total;
Meaning: every time when your if evaluates to false, your method simply returns the value that you assigned initially!
What you could do: have an else block that prints the error message. Or that throws an exception.
But ideally, you should separate concerns here. Meaning:
write a method like boolean inRange(int first, int second). That method returns true or false, depending on first / second matching your criteria
if that method returns true, call compute(), otherwise print your message
In other words: your compute() method maybe shouldn't have that if block at all. Let that method compute the result, and have another method tell you whether you want to invoke compute() or not.
A "ladder" built from ifs behaves as a logical and relation. The first if passes when a condition applies, then the second if passes when both the previous condition applies and its own condition, and so on.
However for checking if something is off, violating any (even a single one) of the rules is enough, that is a logical or relation.
While it is not the best coding style, you could mechanically rewrite that structure into this via flipping the comparisions and dismantling the ladder:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (first > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
This method displays the message and returns with 0 if the input is not valid, and returns the product if everything is fine.
Then it could become an actual logical or, which is denoted as || in Java:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min
|| first > max
|| second < min
|| second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
Now as I think of it, there is nothing wrong with your original condition either, just the result has to be flipped: when the code reaches the innermost block, everything is fine, so that is the place where you could return first*second;. And if any of the if fails, you need the message and return 0;:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
return first*second;
}
}
}
}
System.out.println("Number is not in range, please try again");
return 0;
}
Now I am not so sure if this helps or not...
There you go :
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
if(first<=min || second<=min ||first>=max||second>=max)
{
System.out.println("Number is not in range, please try again");
return 0; //or return whatever you like
}
return first *second ;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
if(total!=0){
System.out.print("Product of x and y = " + total);
}
else {
System.out.print("cannot compute as numbers are not in range");
}
}

How can i calculate the sum correctly without using sum++;?

So I'm working on a project currently and this step asked me to write a program which asks for numbers and when "-1" is entered, it will calculate the sum of all numbers entered except the -1. I simply fixed this by adding +1 after the loop, but im sure there is another "proper" way of doing it and i would like to learn how.
Any help is appreciated. ( Note: I've only been learning Java for around a week so ELI5 please )
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
sum = sum + numbertyped;
}
sum++;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
EDIT: My program is complete now. I used the solution of adding a break in the while loop and after adding the rest of the features i wanted, this is the end product: ( if anyone has tips on how to improve my code or make it more efficient please comment! )
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-3
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int numbertyped = 0;
int sum = 0;
int howmany = 0;
int evencounter = 0;
int oddcounter = 0;
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1)
{
break;
}
if (numbertyped % 2 == 0)
{
evencounter++;
}
else
{
oddcounter++;
}
sum = sum + numbertyped;
howmany++;
}
double average = (double) sum / howmany;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + howmany);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + evencounter);
System.out.println("Odd numbers: " + oddcounter);
}
}
You can terminate your loop as soon as -1 is entered, change
while (numbertyped != -1) {
numbertyped = Integer.parseInt(reader.nextLine());
to something like
while ((numbertyped = Integer.parseInt(reader.nextLine())) != -1) {
// ...
and the loop body will not be entered when -1 is assigned to numbertyped.
Based on your edits, I would suggest you might shorten sum = sum + numbertyped; to sum += numbertyped; and that you can calculate howmany by summing evencounter and oddcounter. Like,
System.out.println("Type numbers: ");
while (true) {
numbertyped = Integer.parseInt(reader.nextLine());
if (numbertyped == -1) {
break;
}
if (numbertyped % 2 == 0) {
evencounter++;
} else {
oddcounter++;
}
sum += numbertyped;
}
int howmany = evencounter + oddcounter;
double average = (double) sum / howmany;
Quite often, C-like language users do not thing of using an "exit loop" (break) in similar situations. You'd want something like this instead:
while (true)
{
numbertyped = Integer.parseInt(reader.nextLine());
if(numbertyped == -1)
{
break;
}
sum = sum + numbertyped;
}
As a side note, a "forever loop" can be written with a for(;;) which some people say is better than a while(true). However, most people view while(true) as easier to read. Personally I use the for(;;). Either way both are optimized properly and thus you will get no runtime difference.
Reference about for(;;):
while (1) Vs. for (;;) Is there a speed difference?
I think in this case, you can just reverse the order of the statements in the while loop.
int numbertyped = 0;
int sum = 0;
System.out.println("Type numbers: ");
while (numbertyped != -1) {
sum = sum + numbertyped;
numbertyped = Integer.parseInt(reader.nextLine());
}
The first time through the loop, numberTyped is 0, which is perfect - it won't exit the loop, and it won't actually add anything to the sum. After that, it won't change the sum until after you've checked whether it's -1.

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

My Euclid Algorithm is working very slowly

This code compiles fine, but when I run it, it asks for my two numbers as expected and then just sits there and doesn't do anything at all. I've searched the Internet and worked on this all day. I'm finally caving and asking for help.
Is the issue that it's not looping back up automatically? After 10 hours at this, I've found nothing.
import java.util.Scanner;
public class EA
{
public static void main (String[] args)
{
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
//do the calculations
while(J>0)
{
int Remainder;
Remainder = I % J;
while(Remainder>0)
{
I = J;
J = Remainder;
return;
}
System.out.println("GCD is" + J);
}
}
}
}
Among other things already mentioned, you are confusing while with if. You have put your algorithm logic inside a while loop that only runs if the first input is bad.
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
// You never reach here under ordinary conditions
}
SJuan mention that the return breaks the loop, which is true, but even if it's fixed there are a few other issues:
The inner while never end (infinite loop)
The result will be stored in J - not in I
System.out.println("GCD is " + I); Should be printed outside of the outer while!
The "heart" of your program should do this:
// we get here with valid values stored in I,J
int Remainder = I % J;
//do the calculations
while(Remainder>0)
{
I = J;
J = Remainder;
Remainder = I % J;
}
System.out.println("GCD is " + J);
There are more than 1 error: the return in the while, the algorithm and the brackets of the first while.
1) When you resolve the issue of zero, the brackets of the while must be closed suddenly after you re-assign the value of the variable J.
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
2) The algorithm for computing the gcd is the following:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod t
a := t
return a
Here is the correct version of your code:
public static void main(final String[] args) {
// get first integer from user
final Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
// resolve the issue of zero
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
// do the calculations
while (J != 0) {
int Remainder;
Remainder = I % J;
I = J;
J = Remainder;
}
System.out.println("GCD is" + I);
}
The return in the middle of the loop will end the execution.
This one
while(Remainder>0)
{
I = J;
J = Remainder;
return; <------- THIS IS THE RETURN THAT BREAKS ALL
}
so it does not get to the System.out.println.
UPDATE: Also, you do input.nextInt() twice for J. Probably from your description, it keeps waiting for you for entering the third integer.
Well Euclid's algorithm has a drawback as both the inputs should be non zero to compute the Greatest common divisor . But if you want to find out the GCD when one of the input is a zero ('0') tweak the logic a bit . When one of the input is zero the GCD is 1, and 'a' should be greater than 'b' to compute GCD. Check the snippet below:
if (a < b) {
int temp = a;
a = b;
b = temp;
}
if (b == 0) {
System.out.println("1");
} else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}

cant get binary to print horizontal and to stop exacution

I am making a program that is converting from decimal to binary, octal, and hexadecimal. I am only focusing on the decimal to binary part in this so far. My problems are that the binary when I ask it to convert up to said number print them vertically not horizontally like 010. Also my while statement does not stop exacution if the y input is greater than 1024, which is the highest value I want to be able to be accepted.
import java.util.Scanner;
public class DNS
{
public static void main(String[] args)
{
int y;
Scanner input = new Scanner( System.in);
do
{
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
for(int x=0; x <=y; x++)
{
convertToBinary(x);
}
}
while(y <=1024);
}
public static void convertToBinary(int x)
{
if(x >0)
{
convertToBinary(x/2);
System.out.print(x%2 + " ");
}
System.out.println("");
}
}
remove System.out.println(""); from public static void convertToBinary(int x)
you will be able to print horizontally
and change your do-while to simple while like this
int y;
Scanner input = new Scanner( System.in);
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
while(y <=1024)
{
for(int x=0; x <=y; x++)
{
convertToBinary(x);
}
}
you were checking if y<=1024 after calling convertToBinary() method. you have check if y<=1024 before making a call to convertToBinary() method.
You probably meant to have the empty System.out.println() call (by the way, you can call it with no arguments) after the call to convertToBinary(x) in the main for loop - otherwise empty lines are being printed during each recursion step of each number being evaluated.
for (int x = 0; x <= y; x++) {
convertToBinary(x);
System.out.println();
}
Regarding your other question about stopping if the input is larger than 1024 - this is because the calls to convertToBinary(x) are happening before the check in the while statement. You will need to explicitly break out of the loop to stop this. Personally, I would just use an infinite while loop with explicit checks:
while (true) {
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
if (y < 0) {
System.out.println("That number is not positive!");
break;
}
if (y > 1024) {
System.out.println("That number is too big!");
break;
}
for (int x = 0; x <= y; x++) {
convertToBinary(x);
System.out.println();
}
}

Categories

Resources