I am having trouble with this simple loop for a uni lab. It wont stop looping until I put in a number over a thousand. I can't see where I have gone wrong on such a simple loop.
I have meant to have written a simple method that will loop through adding numbers until the number is greater than 100 and then once it has reached 100 or greater it will output the total.
public void adder2(){
int sum = 0;
int number = 0;
while(number < 100){
sum = sum + number;
number = getNumber();
}
System.out.println("The result is " + sum);
}
Try this:
while (sum < 100 && number < 100) { ...code as above... }
Related
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:
1 is not a prime number
2 is a prime number
3 is a prime number
and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers
int check;
int number;
boolean prime = true;
for (int i=2; i<=check/2; i++)
{
number = check%i;
if (number == 0)
{
prime = false;
}
}
if (prime == true)
{
System.out.println(check + " is a prime number");
}
else
{
System.out.println(check + " is not a prime number");
}
}
You have almost all of the code correct, you just need to put it in the right place. For example, your println statements need to be inside the for loop and your for loop needs to start at 1 and increment by 1 to 100.
for(int x = 0; x < 101; x++)
{
if(x == 2)
System.out.println(x + " is a prime number");
if(x % 2 == 0)
System.out.println(x + " is not a prime number);
else
System.out.println(x + " is a prime number);
}
I just helped a friend with almost this exact problem, so this couldn't be better timing. I don't know if your scanner is going to be used, but this works if you are just looking for prime numbers from 1-100.
For starters, it seems your Scanner isn't being used anywhere. Maybe your code is incomplete?
You can replace the Scanner part where you get the input from the user with a for loop that will give the number to you. Like so:
for(int number = 1; number <= 100; number++) {
// code for checking if number is prime or not
}
Take a look at code below, let me know if something is unclear, ask, don't just read and copy:
package com.company;
public class Main {
public static void main(String[] args) {
out:
for (int i = 1; i <= 100 ; i++) {
for (int j = 2; j <= i / 2 ; j++) {
if (i % j == 0) {
System.out.println(i + " is not prime number.");
continue out;
}
}
System.out.println(i + " is prime number.");
}
}
}
So to just walk over the code real quick:
1.) Create labeled block called out:
out:
2.) Create two nested for loops to check for our numbers being prime or not
3.) If statement in the second for loop will check if our number is not prime (if it's divisible by any number from 1 to itself but not those two numbers)
4.) In case our evaluation in if statement is false we continue looping until our second loop condition fails, then we move outside of the loop and print that number is prime:
System.out.println(i + " is prime number.");
5.) In case our evaluation in if statement is true we enter the if block, we print that number is not prime and we move program control back to the labeled block we created earlier
6.) We continue doing this repeatedly until outter loop check condition fails and our program is done with it's work.
/* Prime numbers are numbers that are divisible by 1 and by themselves. So, if you take the modulus of a number 'N' with all the number from 1 till 'N' and increase a count each time the modulus is zero, you can use a simple if condition at the end to check whether they are prime or not. In this code, I start from checking with number 1 and go till 100*/
int count ;
for(int j=1;j<=100;j++)
{
count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
count=count+1;
}
if(count>2)
System.out.println(j+"is not a prime number");
else
System.out.println(j+"is a prime number");
}
So, I am working on this code for my AP Computer Science class, and I ran into a problem.
First, here is my code:
//loop counters
int counterOne = 0;
int counterElse = 0;
int loop = 1;
int iNum = 1000;
//create file
PrintWriter outFile = new PrintWriter(new File("newFile.txt"));
for (int counter = 1; counter <= iNum; counter++)
{
while (loop >= 1)
{
Random rand = new Random();
int iRand = rand.nextInt(5)+1;
if (iRand != 1)
{
counterElse++;
loop++;
}//end of if of if-else
else
{
counterOne++;
loop = 0;
}//end of else of if-else
}//end of while loop
int tries = counterElse+counterOne;
//int average = (tries + prevTriesSum) / counter
System.out.println("It took " + tries + " try/tries to win!");
//outFile.println("It tool an average of " + average + " tries to win.");
}//end of for loop
How do I calculate the average of the trials? As you can see from the end of my code, I commented out a line that I would want to calculate the average. This is because I don't know how to calculate prevTriesSum, which represents the sum of all of the other trials. Here is an example: Assume the loop runs six times, and with the first run, it takes 3 tries, 5 on the second run, 7 on the third, 11 on the fourth, 2 on the fifth, and 4 on the sixth (the most recent one. now tries = 4).
I would want prevTriesSum to equal 3 + 5 + 7 + 11 + 2 + 4.
How do I get the program to calculate that?
Your average is computed in integer arithmetic which means any fractional part is discarded. Consider using a floating point type for the average, and prefix the right hand side of the assignment with 1.0 * to force the calculation to occur in floating point.
You must not reinitialise the random generator in the loop, else you ruin its statistical properties. Do it once before you enter the loop.
Before the while loop, add
int prevTriesSum = 0;
Replace your commented int average = line with
prevTriesSum += tries;
And after the for loop add
double average = (prevTriesSum + 0.0) / counter;
outFile.println("It tool an average of " + average + " tries to win.");
As for the random number generator, Bathsheba is correct. You must move that above the for loop. Just move the declaration.
You'll also need to change your for loop slightly. As it stands, it will equal 1001 when the for loop terminates. Change it as follows:
for (int counter = 0; counter < iNum; counter++)
This will ensure that your average calculation is correct.
My assignment asks for a command-line input to be put through nested while loops to find if a number is a happy number or not. So far I have this:
int i = 0;
int sum = 0;
int dig2, dig1, dig3, dig4, dig1next, dig2next, dig3next;
int digit1sum, digit2sum, digit3sum;
happyNumber = number;
while (i < 500){
while (happyNumber > 0){
while (sum!=1){
dig3 = happyNumber / 100;
dig2 = happyNumber % 10;
dig1 = happyNumber / 10;
dig2next = dig2 % 10;
dig1next = dig1 % 10;
dig3next = dig3 % 10;
digit1sum = dig1next * dig1next;
digit2sum = dig2next * dig2next;
digit3sum = dig3next * dig3next;
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
}
System.out.println("It is a happy number.");
System.exit(0);
}
i++;
System.out.println(i);
System.exit(0);
}
I set i<500 so when i++ reaches 500, the loop should stop. I've pretty much tried putting i++ in every section of the code possible, it never works. what am i doing wrong here?
also: i am not allowed to use for loops or do-while loops on this assignment. i have to use nested while loops only
Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1(how long the loop will be: 500).
After a quick glance at your code:
while (sum!=1)
....
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
This while test is likely to be always true -> infinite loop -> stack overflow
You will never get out of your innermost while-loop in case of a number that loops endlessly (it is by no means stopped by the 500- limit and your logic is wrong here).
Secondly, something to think about:
digit1sum = dig1next*dig1next;
digit2sum = dig2next*dig2next;
digit3sum = dig3next*dig3next;
these (digitxsum) will always be positive.
sum = digit1sum + digit2sum + digit3sum;
sum will therefore always be positive
happyNumber = sum;
happynumber will always be positive
while (happyNumber > 0)
what is this for?
I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs.
I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. Any quick fixes for this? :)
import java.util.Scanner;
public class ComputeSumAAndB
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter 2 integers: "); //prompts user for ints
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
for (int j = a; j <= b; j++)
{
if (j % 2 == 1)
sum += j;
}
System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
}
}
int temp;
if(a > b) {
temp = a;
a = b;
b = temp;
}
Put this right before your for loop starts.
The if checks whether a (the first number entered) is larger than b. If it is, it swaps a and b. Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if, a will always be the smaller number).
Using this method has the added side effect of making your output make sense. Your output will now always say: "between [smaller number] and [larger number]".
rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]", etc.
You can get the smaller and larger inputs by using the Math.min() and Math.max functions....
for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
if (j % 2 == 1) {
sum += j;
}
}
It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B.
You could do what nhgrif says but it's changing your data.. But he is correct.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Actually you should do the following 2 things:
1 It is just just like rolfl mentioned above. You need to put the min and max in the right place in loop.
for (int j = Math.min(a,b); j <= Math.max(a,b); j++)
{
if (j % 2 == 1) {
sum += j;
}
}
2 Use if (j % 2 == 1) it is not enough to check whether the num is odd.
e.g.
a = -5, b =0;
What will be the result?
int sum = 0;
for(int j=-5;j<0;j++)
{
if(j%2 == 1)
{
sum+=j;
}
}
The value for sum will be 0.
We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Here's how it's written in the book:
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 10, 50, and 100. Your program should repeat the calculation for new values of x until the user says she or he is through. The expression n! is called the factorial of n and is defined as
n! = 1*2*3*...*n
Use variables of type double to store the factorials (or arrange your calculation to avoid any direct calculation of factorials); otherwise, you are likely to produce integer overflow, that is, integers larger than Java allows."
I don't have any coding problems (not yet at least), my problem is I don't know what it's asking me to do. I get the factorial part (ex. 3i = 1*2*3) but I am just not sure what else it is asking. I have the user input a value for "x" but where does the "n" come from?
"The value e^x can be approximated by the following sum:
1+x+x^2/2!+x^3/3!+...+x^n/n!
" I don't know what this is saying or asking for.
I put together this for loop for the 1-10, 50, 100 part and I don't know if that even makes sense without understanding the rest, but here it is:
for (counter = 1 ; counter <= 100 ;counter++)
{
//System.out.print("Enter value for x: ");
//x = keyIn.nextDouble();
if (counter >= 1 && counter <= 10)
{
if (counter == 1)
System.out.println("Iterations 1-10: ");
System.out.println("test to see if 10 show up");
}
else if (counter == 50)
{
System.out.println("Iteration 50: ");
}
else if (counter == 100)
{
System.out.println("Iteration 100: ");
}
}
I haven't been in algebra in about two years so some of this stuff is throwing me off a bit. Please help with whatever you can, thanks.
It's saying that e^x can be approximated through a Taylor Series: Sum(i:0:n)(xi/fact(i))
So, we have:
double ex_taylor_series(double x, int n)
{
double value;
for(int i = 0; i < n; i++)
{
value += Math.pow(x, i)/(factorial(i));
}
return value;
}
private int factorial (int num)
{
int value = 1;
for(int i = num; i > 1; i--)
{
value *= i;
}
return value;
}
In your case, you would simply feed different values of n, 10, 50 and 100, to ex_taylor_series.