I know the sumOfMultiples method itself works and that the problem lies in the main method. When I run it, nothing happens and it just continuously runs. I'm using netbeans if that makes a difference.
package examp;
public class Main {
public static void main(String[] args) {
Main example = new Main();
System.out.println("The answer is " + example.sumOfMultiples(2, 3));
}
public int sumOfMultiples(int num1, int num2) {
int num1Total = 0;
int num2Total = 0;
//Total of the multiples of the first number.
while (num1 < 1000) {
num1Total = num1Total + num1;
num1 = num1 + num1;
}
//Total of the multiples of the second number.
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
return num1Total + num2Total;
}
}
Sorry if it's a stupid question, just made an account a couple of minutes ago.
Your second while loop doesn't increment num2 (that is why it doesn't stop)
while (num2 < 1000) {
if (num2 % num1 != 0) {
num2Total = num2Total + num2;
}
num2++; // <-- like so.
// or, num2 = num2 + 1;
}
Its in infinite while loop:
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
If you want to debug on your own then run this (I have added couple of System.out.println statements) and you will know how:
public int sumOfMultiples(int num1, int num2) {
int num1Total = 0;
int num2Total = 0;
//Total of the multiples of the first number.
while (num1 < 1000) {
num1Total = num1Total + num1;
num1 = num1 + num1;
System.out.println("num1"+num1);
}
//Total of the multiples of the second number.
System.out.println("num1:"+num1+" "+"num2:"+num2);
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
return num1Total + num2Total;
}
With this you get num1=1024 num2=3 and you can see that it will never go in the if loop so second while loop goes in infinite loop. Once it enters second while loop then num2 remains constant so you need to add some incrementer like num2++ which may allow it to come back after finite loops.
Related
I would like to receive user input on n elements for the Fibonacci sequence. The scanner and calculations themselves seem to be working fine -- the input is successfully grabbed and the sequence calculated. It's even able to correctly disqualify inputs of a negative value. However, it is not actually returning 'n' elements. Curiously, I noticed that the loop consistently returns exactly half the elements requested, albeit in the correct order. If n = 20, the first 10 numbers are returned.
Here's the code:
public class fibonacci_input {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
++i;
}
}
}
}
I'm struggling to imagine what the problem could be. I first thought it might be a problem with the test condition statement, but similar (working) solutions online seem to have their loops formatted almost identically. Is it perhaps a problem with my variable declarations? I've tried multiple changes to no avail so would appreciate another set of eyes :)
You could just delete the second i++; statement in your code, this one is making the for loop run half times as expected, since the i variable is being incremented twice on each iteration
public class fibonacci_input {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
//++i;
}
}
}
}
There are 3 numbers that are given to the user. These three numbers define the multiple, and the range. For example if these three numbers are (3, 6 , 17) the program should print 6,9,12,15. The first number is the base multiple and the second and third numbers are the lowest and the highest numbers (the range). I also know that I do not need all the import statements that I have.
This is what I have so far but I'm not sure how to continue.
import java.util.*;
import java.io.*;
import java.text.*;
import java.lang.Math.*;
public class printMultiplesOf{
public static void main (String [] args){
Scanner reader = new Scanner(System.in);
int num1, num2, num3;
System.out.println("Enter the 1st number");
num1 = reader.nextInt();
System.out.println("Enter the 2nd number");
num2 = reader.nextInt();
System.out.println("Enter the 3rd number");
num3 = reader.nextInt();
printMultiplesOf(num1, num2, num3);
}
public static void printMultiplesOf(int num1, int num2, int num3){
int start = num2
int end = num3
for (int i = num1; i <= num1; i++){
System.out.println(i + " ");
}
}
}
The main issue here is finding the loop's start and end point. The start point needs to the first number divisible by num1 equal or larger than num2. You can find it by dividing num2/num1 using floating-point division, ceil the result and multiply it back by num1. Similarly, the loop's end point should be the largest number divisible by num1 which is less than or equal to num3. You can find it by dividing num3/num1 using integer division (which would effectively floor the result and then multiplying it back again by num1. From there on, it's just a matter of looping in steps the size of num1. E.g.:
public static void printMultiplesOf(int num1, int num2, int num3) {
int start = ((int) Math.ceil((double) num2 / num1)) * num1;
int end = (num3 / num1) * num1;
for (int i = start; i <= end; i+= num1) {
System.out.println (i + " ");
}
}
Loop through all the numbers in the range, and check if it's a multiple.
public static void printMultiplesOf(int num1, int num2, int num3) {
for(int i=num2; i<= num3; i++){
if(i % num1 == 0)
System.out.print(i +" ");
}
}
This is your function. You simply add your num1 to i each time loop is executed.
I tried it and it is working ;)
public static void printMultiplesOf(int num1, int num2, int num3){
int multi = num1;
int start = num2;
int end = num3;
for (int i = start; i <= end; i += multi){
System.out.println(i + " ");
}
}
Can someone explain to me some parts of this code:
public static void sequence(int nterms){
int num1 = 0;
int num2 = 1;
int num = 2;
if (nterms <= 0){
System.out.println("Enter a positive integer");
}
else if (nterms == 1){
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1 );
System.out.println(num2);
while (num < nterms){
int nth = num1 + num2;
System.out.println(nth);
num1 = num2;
num2 = nth;
num++;
}
}
}
The number sequence that's in the output is correct. So the code works. But why do you do num++ in the end? I know nth is previous two numbers added together but why do you nterms == 1 and print "" +num1? I don't get that.
Here it is
public static void sequence(int nterms){
/*instancation of needed variables : nth = num1+numb2 later in the code*/
int num1 = 0;
int num2 = 1;
/*num is the number of term you've encoutered, as the first two are in
the initialization, you start at 2*/
int num = 2;
if (nterms <= 0){ //check wether the function has a correct input or not*/
System.out.println("Enter a positive integer");
}
else if (nterms == 1){ /*if it's the first term we know in num1*/
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1);/*we print the first two terms*/
System.out.println(num2);
while (num < nterms){ /*we loop till we reached the wanted number*/
/*we know a term is equal to the two terms before it, at least I hope you do*/
int nth = num1 + num2;
System.out.println(nth); /*we've got our number so we print it*/
num1 = num2; /*we make sure num1 and num2 are the last two encountered, so num1 becomre num2 and num2 become the current term (nth)*/
num2 = nth;
num++;/*we increment the variable as we've met printed a new term*/
}
}
}
I've gotten my loop to work and exit when the value '999' is entered.
I'm not sure what to do from here as my program isn't functioning exactly how I want it to.
Currently, the loop is exiting after the values 'num1' 'num2' and 'num3' have been fulfilled. I'm wanting the program to exit as soon as the value '999' is entered; not when num1, 2 and 3 have all been entered.
Here's my code:
import java.util.Scanner;
public class SumAverage {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.printf("Please Enter the first number%n");
float num1 = keyboard.nextFloat();
System.out.printf("Please enter the second number%n");
float num2 = keyboard.nextFloat();
System.out.printf("Please enter the third number%n");
float num3 = keyboard.nextFloat();
float sum = (num1 + num2 + num3); //calculates sum
float average = (num1 + num2 + num3) / 3; //calculates average
for(int x = 0; x < 1; x++) {
if (num1 == 999 || num2 == 999 || num3 == 999) {
break;
}
System.out.printf("Sum: %.0f %nAverage: %.2f", sum, average);
}
}
}
If you really want the program to end as soon as a value of 999 is entered, you can change your main() method to this:
public static void main(String[] args) {
System.out.printf("Please Enter the first number%n");
float num1 = keyboard.nextFloat();
if (num1 == 999) {
System.exit(0);
}
System.out.printf("Please enter the second number%n");
float num2 = keyboard.nextFloat();
if (num2 == 999) {
System.exit(0);
}
System.out.printf("Please enter the third number%n");
float num3 = keyboard.nextFloat();
if (num3 == 999) {
System.exit(0);
}
float sum = (num1 + num2 + num3); // calculates sum
float average = (num1 + num2 + num3) / 3; // calculates average
System.out.printf("Sum: %.0f %nAverage: %.2f", sum, average);
}
If we look at the way your code is currently written, the user will always be required to input 3 values due to not having any kind of conditionals attached.
I recommend using "System.exit" with conditionals to test if the value the user is inputting is 999. Try going from there to see what you can make happen.
Here is some documentation regarding "System.exit" to help you gain a better understanding of how it works.
Your for loop is looping only once so what I think you'll need to do is change some aspects of code
public class Calculator{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
float num1;
float num2;
float num3;
while (true){ //This will run forever until we break the loop
num1 = keyboard.nextFloat();
if (num1 == 999){
break;
}
num2 = keyboard.nextFloat ();
if (num2 == 999){
break;
}
num3 = keyboard.nextFloat ();
if (num3 == 999){
break;
}
System.out.println("The average is: " + (num1 +num2+num3)/3);
}
}
}
My code is probably amateur to a lot of you, so if any of my logic in it is messed up, that's okay. I'll fix that later. Just wondering if anyone could let me know why my else statement is coming up with: "Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error on token "else", delete this token"
I read some of the other questions on here and usually the problem is people are checking conditions (else (blah < bleh) {) with else, but I didn't do that.
import java.util.Scanner;
public class minOfThree {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
int num1, num2, num3, num4, min = 0;
System.out.println ("Please enter three numbers.");
System.out.print ("First value: ");
num1=kb.nextInt();
System.out.print ("Second value: ");
num2=kb.nextInt();
System.out.print ("Third value: ");
num3=kb.nextInt();
System.out.print ("Fourth value: ");
num4=kb.nextInt();
if (num1 < num2)
if (num1 < num3)
min=num1;
else
min=num3;
else if (num2 < num3)
min=num2;
else
min = num3;
***else*** {
min = num4;
}
System.out.println ("Minimum value is: " + min);
}
}
This could have been avoided if you used { and } properly:
if(num1 < num2) //"if" for if-else #1
{
if(num1 < num3) //"if" for if-else #2
{
min=num1;
}
else //"else" for if-else #2
{
min=num3;
} //complete end of if-else #2
}
else if(num2 < num3) //"else if" for if-else #1
{
min=num2;
}
else //"else" for if-else #1
{
min = num3;
} //complete end of if-else #1
else //"else" for nonexistent if-else == error
{
min = num4;
}
Here you can see that you have two elses on one if-else statement.
To fix it, use something like this:
min = Integer.MAX_VALUE; //minimum = maximum possible
if(num1 < min) //if num1 is less than current minimum...
{
min = num1; //current minimum = num1
}
if(num2 < min) //if num2 is less than current minimum...
{
min = num2; //current minimum = num2
}
if(num3 < min) //if num3 is less than current minimum...
{
min = num3; //current minimum = num3
}
if(num4 < min) //if num4 is less than current minimum...
{
min = num4; //current minimum = num4
}
There can only be one else for each if/else if. The else if (num2 < num3) part already has an else statement two lines below it. Maybe you are missing an if-statement somewhere?
Get into the habit of always writing if-else statements within brackets, then you will never have to wonder what statement goes with which test. I believe the following is what you want your code to look like:
if (num1 < num2) {
if (num1 < num3) {
min = num1;
} else {
min = num3;
}
} else {
if (num2 < num3) {
min = num2;
} else {
min = num3;
}
} else {
min = num4;
}
Although that does not make full sense because here you get two elses as well.
It happens because the else if doesn't create a new if/else branch. This is the correct indentation of how compiler interprets it.
if (num1 < num2)
if (num1 < num3)
min=num1;
else
min=num3;
else if (num2 < num3)
min=num2;
else
min = num3;
else
min = num4;
As you can see, it is not what you intended. So, as only one else statement is allowed, it doesn't compile. As already suggested, you should use braces.
If it were me, I would just use braces and move on ;-)
if () {
// hack
} else if () {
// hack hack
} else {
// hack hack
}
However, the logic you use is wrong, too, you could replace your last else by
if (min > num4) {
min = num4;
}
As per my knowledge if you are not writing multiple lines inside a scope (i.e. if-else statment), then there is not required of {}.
if (num1 < num2) //1st If Start
if (num1 < num3) //2nd If Start
min=num1;
else
min=num3; //2nd If Ends
else if (num2 < num3) //3rd If starts in else part of 1st If
min=num2;
else
min = num3; //3rd If Ends
***else*** { //This else part is not followed by any If Statement (Causes Error )
min = num4;
}
In this case your approach is correct but, you missed the start point of this last else.
Hope it will help you.
Your logic is amateur but it's ok? You are using two Else statements. That makes no sense. And you don't have brackets encapsulating the routines which is really confusing. What are you even trying to do? Are you trying to find the smallest number? Try this?
public static void main(String[] args){
int num1 = 4;
int num2 = 2;
int num3 = 3;
int num4 = 10;
int array[] = {num1, num2, num3, num4};
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array.length-1; j++)
{
if (array[j] > array [j+1])
{
int x = array[j];
array[j] = array [j+1];
array [j+1] = x;
}
}
}
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
In this case yes because there's no sense of a second else clause. It would be unreachable code
Look at the first if statement. You didn't put the braces and other mistakes you made. like putting two else statements to one if statement.
import java.util.Scanner;
public class StackOver {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
int num1, num2, num3, num4, min = 0;
System.out.println ("Please enter three numbers.");
System.out.print ("First value: ");
num1=kb.nextInt();
System.out.print ("Second value: ");
num2=kb.nextInt();
System.out.print ("Third value: ");
num3=kb.nextInt();
System.out.print ("Fourth value: ");
num4=kb.nextInt();
if (num1 < num2){
if (num1 < num3)
min=num1;
else
min=num3;
}else if (num2 < num3)
min=num2;
else if(num4 < num3)
min = num4;
else
min = num3;
System.out.println ("Minimum value is: " + min);
}
}