So I'm trying to further my knowledge of loops and I'm attempting to satisfy a loop program, ran by a driver.
The final loop to be satisfied should generate a random number between two given bounds, given from the driver, and is to run until the random number is equal to the lower bound. Currently, I'm stuck in an infinite loop.
public void loop4()
{
System.out.println("Loop 4 Output, lowerBound = " + lowerBound +
" upperBound = " + upperBound);
for(int i = 0;i < 10; i++){ //First loop should take 5 trys
int num = (int) (Math.random()* (upperBound - lowerBound));
if(num == lowerBound){
System.out.println(i);
break;
}
else{}
}
System.out.println("-------------");
}
And from the driver:
loopTest.setBounds(9, 9);
loopTest.loop4();
loopTest.setBounds(100, 200);
loopTest.loop4();
loopTest.loop4();
loopTest.loop4();
loopTest.setBounds(100, 50);
loopTest.loop4();
So, of course, I'm simply trying to print the counter, i, once num == lowerBound. However, as stated above, I either get stuck in an infinite loop (when I take the limit away from i, in this case it's at ten, just for the sake of testing), or it simply ignore the loop altogether, and I'm having trouble identifying the problem.
Thanks
I recommend you to use Random library:
import java.util.Random;
public static void loop4()
{
Random rand = new Random();
int lowerBound = 100;
int upperBound = 102;
System.out.println("Loop 4 Output, lowerBound = " + lowerBound +
" upperBound = " + upperBound);
for(int i = 0; i < 10; i++){
// Next line was modified so you get values between lowerBound and upperBound
int num = lowerBound + rand.nextInt(upperBound - lowerBound + 1);
System.out.println(num);
if(num == lowerBound){
System.out.println(i);
break;
}
}
System.out.println("-------------");
}
This isn't really the correct way to approach this problem. Since you are trying to loop an undetermined number of times, calling a method to loop 10 times a piece isn't the best way to solve it.
In this case the "while" loop would be more beneficial, something like:
public void loop4
{
int num;
int i = 0;
while (num != lowerbound)
{
num = (int) (Math.random()* (upperBound - ++lowerBound));
i++;
}
System.out.println(i);
}
This way, you only have to call the loop once
upperBound - lowerBound = 50 - 100 for the latest test.
So you'll get a value between -50 to 0 (excluded) and you try to compare it with 100.
Related
Im trying to create a program to find the length of a given number. I thought i would do this by taking the number and dividing by 10 and then checking to see if the number was <= 0. I dident want to edit the global number so i created a instance version of the number and used that as the condition in the for loop.
So obviously this dident work so naturally i ended up looking in the debugger to figure out what was going on. It looks as if the program is completely skipping over the for loop any help would be appreciated.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber <= 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
}
The program should use the for loop to keep dividing by 10 until the number is = to or less than than zero and for how many times the loop ran should be stored in the number length integer. In this case with the number 12321 the answer should be 6 but it prints 0.
You're telling it to loop while instanceNumber <= 0. The "test" in a for loop is a "keep going" test, not a termination test. The loop continues as long as the test is true.
From your description, you want instanceNumber > 0.
Also note Avinash Gupta's point that with your current code, you'll undercount by one. I'd address that by using a completely different loop:
int numberLength = 0;
int instanceNumber = number;
while (instanceNumber > 0) {
++numberLength;
instanceNumber /= 10;
}
That's nice and unambiguous: If instanceNumber > 0, it increments numberLength, then divides by 10 and tries again.
This will print the correct output
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
for(int i = 0; instanceNumber > 0; i++) {
instanceNumber /= 10;
numberLength = i;
}
System.out.println("Number length = " + (numberLength + 1));
}
Your code will be much more comprehensive if you use while loop for your algorithm.
public static void sumFirstAndLastDigit(int number) {
int numberLength = 0;
int instanceNumber = number;
while(instanceNumber != 0) {
instanceNumber /= 10;
numberLength += 1;
}
System.out.println("Number length = " + numberLength);
// to find length of number loop division by 10
}
Consider even more sophisticated solution:
public static void sumFirstAndLastDigit(int number) {
int numberLength = (int) (Math.log10(number) + 1);
System.out.println("Number length = " + numberLength);
}
Taken from Baeldung
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've been working through the problems on project euler and instead of using bruteforce, I wanted to complete the problems with a quality solution. I built this to find prime numbers, and have been testing it for values. When I look for the 12th prime, it's telling me it's 35 (which it obviously is not).
It should be identifying 35 as not a prime number since all previous primes are added to a list, but something is going wrong here. Any ideas?
public static void main (String[] args) {
int nthTerm = 12;
int count = 3;
int nPrime = 3;
ArrayList<Integer> primeList = new ArrayList<>();
primeList.add(3);
int upperBoundary;
ArrayList<Integer> checkList = new ArrayList<>();
int check;
boolean isPrime;
while (count < nthTerm) {
isPrime = false;
nPrime += 2;
for (int i = 0; i < primeList.size(); i++){
upperBoundary = (int) Math.floor(Math.sqrt(nPrime));
if (primeList.get(i) <= upperBoundary){
checkList.add(primeList.get(i));
}
}
for (int j = 0; j < checkList.size(); j++){
check = checkList.get(j);
if (nPrime % check == 0){
isPrime = false;
break;
} else {
isPrime = true;
primeList.add(nPrime);
}
}
if (isPrime == true) {
count++;
}
}
System.out.println("Prime number " + count + ": " + nPrime);
}
}
First, you don't need to recalculate upperBoundary inside the first for loop. That value isn't changing on each iteration of that loop, so just calculate it in the while loop.
Second, for low values of nPrime you're not adding anything to your checkList. This is the root problem. The value 5 is never added to that list, so both 25 and 35 are identified as prime.
Last, you should debug your code by running it in a debugger, or at least printing out some values at intermediate steps. Looking at all of the values that are identified as prime by your algorithm and that are in your checkList variable should lead you to a solution.
(Also, it would help to explain your approach when posting questions here. It would be easier to understand where your code is going wrong if there was an explanation of what it's trying to do.)
Try this out:
public static void main(String[] args) {
int nthTerm = 12;
int nPrime = 3;
List<Integer> primeList = new ArrayList<>();
primeList.add(2);
primeList.add(3);
while (primeList.size() < nthTerm) {
nPrime += 2;
boolean isPrime = true;
for (int primeIndex = 1; primeIndex < primeList.size(); primeIndex++) {
int prime = primeList.get(primeIndex);
if (nPrime % prime == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeList.add(nPrime);
System.out.println("Prime number " + primeList.size() + ": " + nPrime);
}
}
System.out.println("Prime number " + nthTerm + ": " + nPrime);
}
The problem with your code:
you are adding non primes in the list for example 25. Just because 25 % 3 == 1 (adding in for if not multipple by a prime - not checking ALL)
checklist never cleared - it can contain multiple elements like: 3, 3, 3, 3, 5, ...
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
}
Why does my program skip the while loop?
class DigitRepeat
{
public static void main(String args[])
{
int n=133,dig=3,digit,count=0;
while(n!=0)
{
digit=n%10;
if(dig==digit)
{
count=count++;
}
n=n/10;
}
if(count==0)
System.out.println("digit not found");
else
System.out.println("digit occurs "+count+" times.");
}
}
> count=count++;
should be
> count++;
explain:
> count=count++;
is
a_temp_var=count;
count=count+1;
count=a_temp_var;
equals to:
a_temp_var=count;
count=a_temp_var;
equals to do nothing.
If I look at the code in my IDE it warns
The value changed at count++ is never used.
i.e. it is warning me that the value calculated is discarded.
If I step through the code in my debugger, I can see the loop is executed but the line
count = count++;
does not change count.
You want either
count++;
count+=1;
count=count+1;
I do not know what do you mean that the program skips something.
But I think I can see your bug. It is here:
count=count++;
++ operator increments count after the assumption, so the variable count remains 0 forever.
I think that you wanted to say count++;
You've got a little error in your code:
count = count++;
Should be change to:
count++;
Have a look over here for a running example, all I did was remove the assignment.
(Included for completeness)
int n = 133;
int dig = 3;
int digit;
int count = 0;
while (n != 0)
{
digit = n % 10;
if (dig == digit)
{
count++;
}
n = n / 10;
}
if(count = =0)
System.out.println("digit not found");
else
System.out.println("digit occurs " + count + " times.");
First advice: when you think your program is skipping a loop add a print after the while it will help you narrow down the problem.
Then you have to be careful with post increments. the value countRight is assigned to countLeft then countLeft is incremented but it doesn't matter because the value of count is already set. the value of count is copied therefore when the ++ takes effect its on a different count (sorry if this isn't so clear).
you can use :
count++;
count = count +1;
count += 1;
or count = ++count;
the last one pre increment works because the value is incremented before being copied ^^
(read up on this because it always turns up in interviews ^^
Here is kinda what you're trying to code in C#:
class Program
{
static void Main(string[] args)
{
var number = 12289;
var search = 2;
var count = Search(number, search);
}
static int Search(int number, int search)
{
return number < 10 ?
(number == search ? 1 : 0) :
(number % 10 == search ? 1 : 0)
+ Search((int)Math.Floor(number / (double)10), search);
}
}