I'm writing a code which will be multiplying 'x' until it'll reach the 'y'.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
do {
x = (int)(x*(1.1f));
}
while(x < y);
}
In the answer I have to get the amount of times 'while' was executed. I'm not sure how to do this.
So general approach would be, create variable i of type int, and increment it at the end of while loop block (this one looks simple actually). So overall, I'd do it this way:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
do {
x = (int)(x*(1.1f));
i++;
} while (x < y);
System.out.println("Loop executed " + i + " times.");
}
If you can use for loop, check out this way of solving your problem:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
for (; x < y; i++)
x = (int)(x*(1.1f));
System.out.println("Loop executed " + i + " times.");
}
}
Thanks to the fact that for loop allows execution of some statement every iteration, you can increment your counter variable everytime loop is looping (this can solve some cases where you use continue; statement).
Basically you need to find out how many times x should be multiplied by 1.1 for it to get larger than y. Or in other words, to what power should 1.1 be raised in order for it to get larger than y/x.
Therefore, an alternative to using a counter would be observing that you need to calculate log1.1(y/x) and round it up to the next int, which in Java can be done with:
Math.ceil (Math.log ((double)y/x) / Math.log (1.1));
Related
I am writing a program that asks the user to input a positive integer and to calculate the sum from 1 to that number. Need some tips on what i'm doing wrong.
Here is the code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a positive integer");
int getNumber=keyboard.nextInt();
int x;
int total = 0;
for (x=1;x<=getNumber;x++) {
total=x+1;
}
System.out.println(total);
}
Try below code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a positive integer");
int getNumber = keyboard.nextInt();
int x;
int total = 0;
for (x=1;x <= getNumber;x++) {
total += x;
}
System.out.println(total);
}
The logic should be changed from
total=x+1; // you evaluate total each iteration to initialize it with x+1
to
total=total+x; // you keep adding to the existing value of total in each iteration
to get the sum from 1 to the input number you want to increment total by each time with the new number x.
so do total = total + x.
also a tip:
you want to declare int x with your for loop. delete int x and do the following:
for (int x=1; x<=getNumber; x++) {
total = total + x;
}
Your issue is:
your total value is wrong, Because of this line:
total=x+1;
It should be:
total = total + x;
Change this:
total=x+1;
to this:
total=total+x;
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);
}
}
I received that task:
"A small method, calculateProduct is to be written. It will ask the user to enter two int values, and then calculate and display the product of all the values between the two values entered. For example if the user enters the numbers 2 and 5 the program will display the result 120 (calculated as 2 * 3 * 4 * 5)"
I tried to build something like this:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
int b;
int big;
int small;
//ask to insert two variables
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
// compare two variables
// set the biggest variables to b, the smallest - to a
if (a >=b){
big=a;
small=b;
}
else {
big=b;
small=a;
}
// set the do while loop to complete the code. Run multiplying before counter won't fit to b variable
int result = small;
for (int i=small; i<=big;i++){
result*=i;
}
System.out.println("the multiplication progression between "+small+" and "+big+" equals to "+result);
}
}
However, when I insert 2 and 5 the result is 240. Does anybody know how to fix it? thanks!
Change loop to:
for (int i = small + 1; i <= big; i++)
{
result *= i;
}
you init result with small then multiply it by small again.
Fix: Start the for statement with small+1
...
int result = small;
for (int i=small+1; i<=big;i++){
result*=i;
}
....
The other obvious solution here is to change the init statement from
int result = small;
to
int result = 1;
In that case you don't have to touch your looping code.
And for the record: "small" is a rather bad name here, why not call it "smallerInput" or something like that.
Finally: you could avoid dealing with "small" - if a < b you can simply loop from a to b; and otherwise you could loop "backwards" from "b to a".
Just change your for loop as below mentioned will solve your problem.
The problem in your loop is :
In its first iteration it is multiple with itself rather than its
incremented value.
From:
for (int i=small; i<=big;i++)
To:
for (int i=small+1; i<=big;i++)
The task is to write a method called "calculateProduct". Above you are doing all your callculation in your main method. Try to separate that. Example :
import java.util.Scanner;
public class Exam {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int a;
int b;
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
if(a>=b){
calculateProduct(b,a);
}
else{
calculateProduct(a,b);
}
}
public static void calculateProduct (int m, int n) {
int result = 1;
for (int i = m; i <= n; i++) {
result *= i;
}
System.out.println("the multiplication progression between "+m+" and "+n+" equals to "+result);
}
}
UPDATED
How can you by using this method (Collatz conjecture) to find the number with the highest number of operations between, say 4 and 230.
Any guidance appreciated.
public static void main(String[] args) {
System.out.print("Enter a low integer ");
Scanner input = new Scanner(System.in);
int low = input.nextInt();
System.out.print("Enter a high integer ");
int number = input.nextInt();
maxendurance(number);
}
public static int maxendurance(int number) {
int count = 0;
System.out.print("The number " + number);
// need to loop this i suppose in relative to user input
while (number != 1) {
number = (number & 1) != 0 ? number * 3 + 1 : number >> 1;
count++;
}
System.out.println(" has endurance: " + count);
return number;
}
You will have to loop through all the numbers between low and high. Look into for-loops:
for(int number = low; number <= high; number++)
{
// do something with number
}
Somehow you will need to execute a for every number within the loop (hint: pass it in as a parameter). Then keep track of the number with the highest count.
Oh, and please name your methods more clearly than a and b - nobody will understand what they do without going through the code.
First of all, move the input out of method a:
public static void main(String[] args) {
System.out.print("Enter an integer to be checked: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
a(number);
b();
}
public static int a(int number) {
int count = 0;
System.out.print("The number " + number);
[...]
Then you can use a simple for loop to iterate between low and high:
int bestNumber = -1;
int bestScore = -1;
for (int i = low; i <= high; i++) {
int score = a(i);
if (score < bestScore) {
bestNumber = i;
bestScore = score;
}
}
The result can then be found in bestNumber.
I am going to suggest a more advanced approach, in case relevant and incase anyone comes upon this. If you are concerned about time efficiency, Memoization or Dynamic Programming can help you, especially inverse dragon recursion.
I'll give you a hint. If you need more, just comment.
Take 3 for example. One transformation T has T(3)=10. If prior you had found it takes v transformations to take 10 to 1 and you stored (10,v) in a map, then instantly you know that it takes (v+1) steps to get 3 to 1.
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();
}
}