Is The First Number a Multiple of the Second Number - java

I am writing a program that asks the user to input two integers a total of ten separate times.
Next the program needs to evaluate whether or not the first integer is a multiple of the second integer.
If the first is a multiple of the second then the program should print out "true," if it is not then it should print out "false."
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0; // Initializes the counter
System.out.printf("Enter first integer: "); // asks the user for the first integer
int number1 = input.nextInt(); // stores users input for the first integer
System.out.printf("Enter second integer: "); // asks the user for the second integer
int number2 = input.nextInt(); // stores the users input for the second integer
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 & number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}
} // end class
Somewhere along the line my code is breaking. Is there anyone who can help, or at least point me in the right direction?

You need to read two inputs 10 times. And test if number1 is a multiple of number2. Something like
public static void main(String str[]) throws IOException {
Scanner input = new Scanner(System.in);
for (int counter = 0; counter < 10; counter++) {
System.out.printf("Enter first integer for counter %d: ", counter);
int number1 = input.nextInt();
System.out.printf("Enter second integer for counter %d: ", counter);
int number2 = input.nextInt();
// Since you want to print true if number1 is a multiple of number2.
System.out.println(number1 % number2 == 0);
}
}

& is the bitwise logical AND function. I'm quite sure that won't do what you want it to do. Seems like you want the MODULO operator, %.
E.g. Use number1 % number2. instead of number1 & number2
while (counter <= 10) // starts a loop that goes to 10
{
if (number1 % number2 == 0) // checks to see if number1 is a multiple of number2
System.out.print("true"); // if so then print out "true"
else
System.out.print("false"); // otherwise print out "false"
}

Related

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

While loop will not continue to ask the user for an input

I am very new to java and I need help. Basically, I have a program that asks the user to input a number. When the number is input, it takes a sum of all of the odd numbers before that number and adds them up. What I'm trying (and failing) to do is, make another loop whereby, when the user is prompted to ask for a number to sum up the odd numbers, I want to make it so that it will only continue when an odd number is entered, otherwise it will keep repeatedly asking the user until they enter an odd number. I know that using a while loop will solve this issue, but I'm not sure how to get it to work.
Here's my code:
import java.util.Scanner;
public class OddCalculator {
private static Scanner sc;
public static void main(String[] args)
{
int number, i, oddSum = 0;
sc = new Scanner(System.in);
System.out.print(" Please Enter any Number : ");
number = sc.nextInt();
while (number % 2 !=0) //HERE IS WHERE IM HAVING THE ISSUE
{
continue;
}
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\n The Sum of Odd Numbers upto " + number + " = " + oddSum);
}
}
Thanks in advance!
continue; as a statement scans 'upwards and outwards' for the first construct that can be continued. Things that can be continued are currently only for, while and do/while statements, so it finds while (number % 2 != 0) and will continue it.
To continue a while loop means: Jump straight back to the condition number %2 != 0, evaluate it, and then enter the loop again if it is true, or hop to the } if it is false.
So, your code checks if the number is odd. If it is, it will .. continue. So, it will.. check if the number is odd. If it is, it will check if the number is odd. If it is, it will check if the number is odd.... forever.
Presumably your intent is to ask the user again, but then you'd have to wrap the loop around more code: Start with the print, because certainly sc.nextInt() needs to be inside the loop. That does mean you won't have a number value to check, but that's what do/while loops are for: To guarantee you loop at least once (and so that you can use anything calculated in the loop as part of the condition).
You should also use the scanner inside the while loop in case the number is not odd.
while (number % 2 !=0) {
number = sc.nextInt(); // Use here as well to keep asking for a number until is odd
}
Your confusion seems to be coming from misunderstanding that continue means going back to the while loop, and break is what gets you out of the loop. Does this work for you?
System.out.println(" Please Enter any Number : ");
number = sc.nextInt();
// keep asking for a number for as long as it is even (condition is false on odd)
while (number % 2 == 0) {
System.out.println("Please enter another number: ");
number = sc.nextInt();
}
System.out.println(number + " is now odd!");
I hope this output is what you are looking for, the reason why your previous code doesn't work is that number = sc.nextInt(); is the reason why you can prompt the user for an input, so you have to loop it, furthermore, you can give a specific prompt base on what the user has inputted in the if statement, hope this helps!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// int number, i, oddSum = 0;
int number, i, oddSum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter any Number : ");
do{
number = sc.nextInt();
if(number % 2 == 0){
System.out.print("Please Enter an odd number!: ");
}
}while(number % 2 == 0);
for(i = 1; i <= number; i++)
{
if(i % 2 != 0)
{
oddSum = oddSum + i;
}
}
System.out.println("\nThe Sum of Odd Numbers up to " + number + " = " + oddSum);
}
}
Output:
Please Enter any Number : 2
Please Enter an odd number!: 2
Please Enter an odd number!: 3
The Sum of Odd Numbers up to 3 = 4

how do I display the correct output when no positve numbers are entered

I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.
The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
int sumOfNumbers = 0;
double averagePositive = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0)
break;
if (number > 0)
sumOfNumbers = number + sumOfNumbers;
if (number > 0)
numbers = numbers + 1;
if (number > 0)
averagePositive = (double)sumOfNumbers / (double)numbers;
}
System.out.println(averagePositive);
}
Try it as follows...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Give a number: ");
int num=input.nextInt();
int tot=0; //total
int count=0; // counting the positive numbers
if(num>0){
while(num!=0){
tot+=num;
count++;
System.out.print("Give a number: ");
num=input.nextInt();
if(num<0){
System.out.print("Not possible");
return;
}
}
double avg =(double)tot/n;
System.out.print("Average: "+avg);
}else{
System.out.println("Cannot calculate the average.");
}
}
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.
In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.
continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.
Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.
import java.util.Scanner;
public class avg
{
static int count = 0;
static double sum = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");
while (true) {
System.out.print("Number? ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Negative numbers not allowed.");
continue;
} else if (n == 0)
break;
sum += (double)n;
++count;
}
System.out.println("Average of " + count + " numbers = " +
(double)(sum / count) + "\n");
System.exit(1);
}
}
Sample output:
$ java avg
Enter a sequence of positive numbers (0 to calculate average)
Number? 1
Number? 2
Number? 3
Number? 4
Number? 5
Number? -6
Negative numbers not allowed.
Number? 0
Average of 5 numbers = 3.0

Scanned input inside a do-while loop doesn't reset properly on the next iteration

My program is meant to add up all the even integers between 2 and an input number which is between 20 and 60. The logic for that is correct and will work, but it's supposed to be able to run again if the user wishes, and when it runs again, the input only changes if you input a new integer higher than the previous iteration. If you enter one lower, it just uses the same integer input as before. Here is the code:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number
for no): ");
restart = scan.nextInt();
} while (restart == 1);
}
}
So for example, if I enter 20 as the input, the program outputs:
Sum of even numbers between 2 and 20 is: 110
Enter a new value? (1 for yes, any other number for no):
and then I enter 30 (same run of the program):
Sum of even numbers between 2 and 30 is: 240
Enter a new value? (1 for yes, any other number for no):
and then I try to enter 20 again:
Sum of even numbers between 2 and 20 is: 240
Enter a new value? (1 for yes, any other number for no):
(Should clearly be 110, not 240)
My initial thought was that it wasn't actually scanning for a new input on the second iteration, but because it will work if I keep giving it inputs of greater value I know that is not true.
Use this code inside main()
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
i = 2;
sum = 0;
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number for no): ");
restart = scan.nextInt();
} while (restart == 1);

Using a while loop to take in a string of numbers and then returning the average

Hello I am writing a program that wants me to take in a user input and return the average of the input the user has to enter (0) to stop the program. My issues come in the incriminating the user numbers, I cant seem to get it to add the numbers in the array together.
Here is the code..
public class Week2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
// TODO code application logic here
Scanner input = new Scanner(System.in);
int n;
int sum = 0;
System.out.println("Input some postive integers (0) to stop.");
n = input.nextInt();
while (n != 0) { // while loop
System.out.println("Please enter (0) to stop");
sum = sum + n;
n = input.nextInt();
the sum = sum + n; is the variable I want to use to add up the numbers but when I run the program and hit 0 it just says hit (0) to stop for every user imputed number.
I added a close brace and a print statement after your loop,
while (n != 0) { // while loop
System.out.println("Please enter (0) to stop");
sum = sum + n;
n = input.nextInt();
} // <-- here
System.out.printf("The sum is %d%n", sum);
And it works here.

Categories

Resources