Hi i want to learn how to do java loop that will determined the number if it is an odd or even like
1st value: 8
2nd value: 15
output:
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
You can do it like so:
Scanner input = new Scanner(System.in);
System.out.print("First value: ");
int start = Integer.parseInt(input.nextLine());//Gets the first number
System.out.print("Second value: ");
int end = Integer.parseInt(input.nextLine());//Gets the second number
for(int i = start; i <= end; i++){
if(i%2==0){//When the number is divided by 2, it gives a remainder of 0. Modulus helps us get the remainder.
System.out.println(i+" is even");
}else{//Doesn't satisfy the first condition. It must be odd.
System.out.println(i+" is odd");
}
}
We use a Scanner to read the user input, then use a for loop and leverage modulus (%). Modulus calculates the remainder of a number after dividing it by a certain number. If a number divided by 2 gives a remainder of 0, that means it is divisible by 2. We can construct an if statement to check whether it is divisble.
Test Run
First value: 1
Second value: 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Hey you can use a for loop it's simple.
for(int i=8;i<=15;i++){
if(i%2==0){
System.out.println(i+"is even");
}else{
System.out.println(i+"is odd");
}
}
And I expect you know how to ask inputs so just pass it on the place of 8 and 15
The short version:
https://www.youtube.com/watch?v=cakN0XC6CcQ
Use number % 2 == 0 for even numbers.
The long version:
// Create a new Scanner() to scan System.in
Scanner scanner = new Scanner(System.in);
// Get the two inputs
int first = scanner.nextInt();
int second = scanner.nextInt();
// Start i as the first number
// While it is less than or equal to the second
// Add one each time
for(int i = first; i <= second; i++) {
// Is there a remainder from dividing i by 2?
// If no, it's even
boolean even = i % 2 == 0;
// Print it
System.out.println(i + " is even: " + even);
}
scanner.close();
Related
I'm 100% new to java. Cannot use string or "breaks" or arrays to solve the problem. Any feedback is great :)
Roadmap is:
Name the number from the user input.
Declare and initialize a counter variable to zero.
Save the right-most digit of input in a variable using the modulo
operator: rightMost = input % 10
Update the value of input = input/10
Determine if the rightMost digit is odd. Use a divisibility test using the modulo operator %.
if rightMost is odd, increase the counter by 1.
if rightMost is even, do nothing.
if the input is not zero, go to step 3.
if the input is zero, the program has reached the last digit and it needs to go to step 10.
Display the results. the counter will have the value of the number of odd digits in the original number.
My code is below: (I probably haven't made it far, but I'm trying)( i likely might need to do a while or do while method)( any guide that has !, =< as a list would be appreciative)
import java.util.Scanner;
public class Labtwo
{
public static void main(String[] args)
{
System.out.print("Please enter an integer:");// program lets user know to input a number
// allow keyboard access for user
// likely in a while or do while method?
Scanner kbd = new Scanner(System.in); // allows user input labels it as kbd
int input = kbd.nextInt();// kbd new value is input as a integer
//int counter = 0;
int rightMosteven= 0;
int rightMostodd = 0;
while (input > 0){
int rightMost = (input % 10);
if(rightMost%2==0)
rightMosteven ++;
else
rightMostodd++;
input=input/10;
}
System.out.printf("Number of odd digits: "+ rightMostodd);
//System.out.printf("Number of even digits: "+ rightMosteven);
}
}
This is my new code updated im just not sure if == is considered a string if it is then my answer is 0 as stated by the "cannot use section"
This answer assumes that you want to count the number of odd digits which some input number has. In fact, using the modulus is one viable way to do this. Consider this version:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int counter = 0;
while (input > 0) {
if (input % 2 != 0) {
++counter;
}
input /= 10;
}
Here is a breakdown of what would happen for an example input of 12345:
1234 => last digit even, counter = 0
divide input by 10
123 => last digit odd, counter = 1
divide input by 10
12 => last digit even, counter = 1
divide input by 10
1 => last digit odd, counter = 2
divide input by 10
0 => terminate while loop
I am making a program that accepts user input to subtract all the numbers desired by the user
I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count<=inputNum; Count++), so that the program loops for user input, based on the inputNum.
Unfortunately, the output is wrong. I can't understand how this would work properly.
I've tried switching the operator in difference by making difference =- toBeSubtracted; into difference -= toBeSubtracted;
For difference =- toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -5
For difference -= toBeSubtracted;, here is a sample output
run:
How many numbers do you want to subtract?
2
Input numbers you want to subtract:
10
5
The difference of those numbers is -15
Here is the code:
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
int toBeSubtracted = scan.nextInt();
difference =- toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
Ok this might help you out:
difference = 0
and than you have:
difference -= toBesubtracted
so what you are doing is:
difference = difference - toBeSubtracted
which in terms is
difference = 0 - 10
difference = -10 - 5
thus you get -15
and where you have
difference =- toBeSubtracted
it is the same as
difference = -1 * toBeSubtracted
thus you get -5
I suppose you want output of 5. Here is your code with one change
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = scan.nextInt(); // so read in the first number here.
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1;Count<inputNum; Count++) // go till from 1 to inputNum - 1 because you have already got one number above
{
int toBeSubtracted = scan.nextInt();
difference -= toBeSubtracted;
}
System.out.println("The difference of those numbers is " + difference);
}
}
You need to understand the operator shorthand notation. You should write -= for minus shorthand. The shorthand is equal to difference =difference - tobesubstracted. Since your initial value is 0 it becomes 0-10-5= -15.
Assign the first value as difference and then do the substraction of next values.
So something like:
difference = scanner.nextInt();
And then do the loop for rest of the values to minus from initial value.
The problem isn’t that your program is working incorrectly.
The problem is that the requirements are nonsense. You can have the difference between two numbers. The difference between 19 and 8 is 11. There is no such thing as the difference between 3 or more numbers. Therefore no program could ever produce that.
That said, Davis Herring is correct in the comment: there is no =- operator. You tried to use one in the line:
difference =- toBeSubtracted;
But the line is understood as just:
difference = -toBeSubtracted;
So your program just outputs the negative of the last entered number. I tried entering three numbers, 11, 3 and 5. The first time through the loop difference is set to -11. Next time this value is overwritten and -3 is set instead. In the final iteration the difference is set to -5, which “wins” and is output.
Instead I suggest that your program should always subtract 2 numbers, as you are also trying in your example. So the user needs not enter the number of numbers, but is just told to enter the two numbers. Then you also don’t need any loop. Just read the first number, read the second number, subtract the second from the first (or the first from the second, or the smaller from the larger, what you want) and print the result. I am leaving the coding to you to avoid spoiling it.
I did this
import java.util.*;
public class ForLoops_Difference
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("How many numbers do you want to subtract? ");
int inputNum = scan.nextInt();
int difference = 0;
int currentNumber = 0; //current number from scanner
System.out.println("Input numbers you want to subtract: ");
for (int Count = 1 ;Count<=inputNum; Count++)
{
if(Count == 1)
{
//nothing to subtract if count is 1
currentNumber = scan.nextInt();
difference = currentNumber;
}
else {
currentNumber = scan.nextInt();
difference = difference - currentNumber;
}
}
System.out.println("The difference of those numbers is " + difference);
}
}
You started your difference at 0. So if you subtracted two numbers, 15 and 3, then you would get 0 - 15 - 3 = -18. I set the difference equal to the first number, 15 in the first loop. Then it should work correctly because you do 15 - 3 = 12.
This program asks the user for a minimum number greater than 1 and a maximum number grater than the min. It then prints out number by number what its divisible by, if its prime or composite, and if its a perfect number in this format:
2 is divisible by 1
2 is prime.
2 is not perfect
3 is divisible by 1
3 is prime.
3 is not perfect
4 is divisible by 1 2
4 is composite.
4 is not perfect.
5 is divisible by 1
5 is prime.
5 is not perfect
6 is divisible by 1 2 3
6 is composite.
6 is perfect.
At the end it displays the number of prime and perfect numbers. The program works but I am wondering if there are any ways to clean up the code/make it more efficient(or if there is anything im doing wrong)
Code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int min;
int max;
//declaring min and max values
System.out.println("Enter minimum value to check (an integer greater than 1:)");
min=input.nextInt();
while(!(min>1)) {
System.out.println("The entry is valid. Please be sure to enter an integer greater than 1");
System.out.println();
System.out.println("Enter minimum value to check (an integer greater than 1:)");
min=input.nextInt();
}
System.out.println("Enter maximum value to check (an integer greater than your min value:)");
max=input.nextInt();
while(!(max>min)) {
System.out.println("The entry is valid. Please be sure to enter an integer greater than the min value");
System.out.println();
System.out.println("Enter maximum value to check (an integer greater than min:)");
max=input.nextInt();
}
//declaring count and tracking variables
int count;
int numPrime=0;
int numPerfect=0;
int temp=1;
String result=" ";
boolean isPrime=true;
boolean isPerfect=false;
int i;
//main loop
for(count=min;count<=max;count++) {
for(i=2;i<=count;i++) {
if(count%i==0&&i!=count) {
isPrime=false;
result=result+i+" ";
temp+=i;
}
else
isPrime=true;
}
//Perfect counter
if(temp==count) {
isPerfect=true;
numPerfect=numPerfect+1;
}
else
isPerfect=false;
//Composite print
if(!(result.equals(" "))) {
System.out.println(count+" is divisible by 1"+result);
System.out.println(count+" is composite.");
if(isPerfect==true)
System.out.println(count+" is perfect.");
else
System.out.println(count+ " is not perfect.");
System.out.println();
}
//Prime print
else {
numPrime=numPrime+1;
System.out.println(count+" is divisible by 1");
System.out.println(count+" is prime.");
System.out.println(count+" is not perfect");
System.out.println();
}
//reset values
result=" ";
temp=1;
}
System.out.println("Primes found: "+numPrime);
System.out.println("Perfect numbers found: "+numPerfect);
}
}
I have a hobby of making my python perfect number code as efficient as possible so I know a few extra efficiency things but unfortunately I don't code Java so these will just be some generic efficiency improvements.
Firstly, as has been hinted in the comments you only have to check to the square root of the number to get all the divisors but what you do have to do is then add the number / your divisors to your list of divisors to get every divisor
e.g. Find the divisors of 20
The square root of 20 is 4.47 so we choose 4.
20 mod 1 == 0 so we add 1 and 20/1 a.k.a. 20 to our list of divisors
20 mod 2 == 0 so we add 2 and 20/2 a.k.a 10 to our list of divisors
20 mod 3 == 2 so we ignore this one.
20 mod 4 == 0 so we add 4 and 20/4 a.k.a. 5 to our list of divisors
Therefore the divisors are 1, 2, 4, 5, 10 and 20.
Another good efficiency improvement is that all perfect numbers will end in 6 or 28 so you can quickly check that.
The last efficiency improvement I know is a big change to the prime calculation bit.
If a number is smaller than or equal to 1 it is not prime.
Else if a number is smaller than or equal to 3 it is prime.
Else if a number mod 2 or a number mod 3 == 0 it is not prime.
Set i to 5
While i squared is smaller than or equal to a number:
If a number mod i or a number mod (i + 2) == 0:
It is not prime
6 is added to i
If nothing has said otherwise then the number is prime.
I am a beginner in Java, can somebody please explain me how the total is 11.
Question - The user is ready to enter in these numbers one by one until the program stops:
4 7 5 8 9 3 4 1 5 3 5
What is displayed as the total?
int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
}
System.out.println(total);
I'll explain step by step.
Step - 1:
You've declared two integer variables. One for holding the input, and another for holding the total value after your calculation. The integer total is initialized as 0. The following part of your code is doing this:
int number;
int total = 0;
Step - 2:
Now you're providing input values. Then the input values are entering the while loop. The while loop will continue to execute unless your input value is 1. Your first input is 4, 4!=1, so, it enters the loop.
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
Step - 3:
Now, inside your loop, you're checking whether your input value is less than 5 or not. If it's less than 5, then total value will be incremented to total + number. Else, total remains unchanged. Regardless of the if condition, your system will continue to prompt you to provide number inputs as long as it's not 1. The following code does this:
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
}
In this case, your input sequence is 4 7 5 8 9 3 4 1 5 3 5.
For first input 4, 4 < 5, which is true, so total = 0 + 4 = 4. The next input is 7, 7 < 5 is false, so total remains 4, same goes for inputs 5 through 9. When your input is 3, 3 < 5 is true, so total = 4 + 3 = 7. Then for input 4, 4 < 5 is true again, so total = 7 + 4 = 11
As we've already seen, the above while loop will terminate, as soon as you input 1. Your next input is 1, so the loop will terminate, you can't input any more number, and your final total value remains 11.
Step - 4:
Outside the loop, you're printing the value of total, so it will display 11.
System.out.println(total);
p.s.
If you understood my solution, your next task will be to do the exact same thing using for loop.
You are entering 4 7 5 8 9 3 4 1 5 3 5
The following code only allows 4 7 5 8 9 3 4 to be accepted cause it breaks from the loop when 1 is entered.
while (number != 1)
{
...
}
More over the following code only adds 4 3 4 because number should be less than 5
if (number < 5) total = total + number;
Hence you get 4 + 3 + 4 = 11
While loop will run till the user enters 1.
And the numbers will sum up if the number entered is less than 5.
So from what the user has entered, it will be 4+3+4 = 11. At 1, the while loop will exit.
int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt();
while (number != 1)
{
if (number < 5) total = total + number;
// only adds 4 3 4 because number should be less than 5
System.out.print("Enter a number");
number = input.nextInt();
}
System.out.println(total);
// Because of that you can: 4+3+4 = 11
your while loop will run until it gets 1 as input.
while (number != 1)
Inside while loop you have a if clause it will add your input to total when entered number is less than 5
if (number < 5) total = total + number;
that's why only adds 4, 3, 4 and total=11
Your input is 4 7 5 8 9 3 4 1 5 3 5
Your code snippet with explanation as comment is given below:
int number;
int total = 0;
System.out.print("Enter a number");
number = input.nextInt(); // your first input number ie. 4 is taken as input
while (number != 1) // while starts because 4 > 1
{
if (number < 5) total = total + number;
System.out.print("Enter a number");
number = input.nextInt();
/* in while loop only 4,3,4 will be added to the total because you have **if (number < 5) total = total + number;** loop will break after taking input 1 because of **while (number != 1)**. At that time total will be equal to 11. */
}
System.out.println(total); // outside loop value of total = 11 will be printed
I am trying to find the even sum and even max from numbers inputted by the user. For example, if they answered "How many integers?" with 4 and inputted the integers: 2, 9, 18, 4 it should output:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 24
even max = 18
Here is my code:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
//prompt user to enter the first integer
System.out.print("next integer? ");
int firstNum = console.nextInt();
//set the even max to the firstNum
int evenMax = firstNum;
//set the evenSum to zero
int evenSum = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 2; i <= numbers; i++) {
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the first number is even
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
//check to see if the numbers entered are even
if (num % 2 == 0) {
//if they are even add them to the evenSum
evenSum += num;
}
//check to see if the number entered is bigger than the first number
if (num > firstNum) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
But here is what is my output is:
how many integers? 4
next integer? 2
next integer? 9
next integer? 18
next integer? 4
even sum = 28
even max = 4
Could someone help me figure out what the problem is?
You were doing some really weird stuff where the first time a number was entered it was treated as special. This was causing the first even number entered (2, in this case) to be added multiple times to the total.
Put all of your input in the same loop so you can treat everything equally:
public static void evenSum(){
//prompt the user to enter the amount of integers
Scanner console = new Scanner(System.in);
System.out.print("how many integers? ");
int numbers = console.nextInt();
int evenSum = 0;
int evenMax = 0;
//for loop for the number of times to ask user to input numbers
for (int i = 0; i < numbers; i++) {
//input new number
System.out.print("next integer? ");
int num = console.nextInt();
//check to see if the number is even. if it is not even,
//we don't care about it at all and just go to the next one
if (num % 2 == 0){
//add it to the sum
evenSum += num;
//if it's larger than the maximum, set the new maximum
if (num > evenMax) {
evenMax = num;
}
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
As you can see, this code also only checks to see if a number is even once. There is no need to be continuously checking if num is even every time you use it: its value is not changing during the duration of a single run of the loop.
Move the following code inside the for loop to just before the for loop-
if (firstNum % 2 == 0){
//if it is even then add it to the evenSum
evenSum += firstNum;
}
This will prevent the repeated addition of the first number in the evenSum
You also want
if (num > evenMax) {
if (num % 2 == 0 ) {
evenMax = num;
}
}
or, alternatively
if (num > evenMax && num % 2 == 0) {
evenMax = num;
}
In your scenario, firstNum is 2 so every number after it is technically larger, so you will (theoretically) not get the largest even number entered after the first number.
Either move the first if condition inside the for loop upwards (outside of the for loop)
or store all of the user inputs in a data structure i.e. Array before processing them.
Storing them in Array would make it easier to manipulate the data.
Working code:-
Scanner console = new Scanner(System.in);
int numbers =0, firstNum =0, num =0 ;
System.out.print("how many integers? ");
numbers = console.nextInt();
System.out.print("next integer? ");
firstNum = console.nextInt();
int evenMax = 0;
int evenSum = 0;
if(firstNum%2==0)
{
evenSum = firstNum;
evenMax = firstNum;
}
for (int i = 1; i < numbers; i++) {
System.out.print("next integer? ");
num = console.nextInt();
if (num % 2 == 0) {
//don't add firstNum multiple times to the evenSum, earlier it was added every time you entered an even number
evenSum += num;
//check if the number you entered, i.e. num greater than the already existing greatest number i.e. evenMax and if so update it
evenMax = num > evenMax: num?evenMax;
}
}
System.out.println("even sum = " +evenSum);
System.out.println("even max = " +evenMax);
}
Hope this helps. There are three major problems in your code:-
The firstNum(if it's even) gets added to the sum every time you enter a even number. i.e. if first number is 4 and the loop runs 10 times and encounter 6 even numbers, then along with the even number 4 also gets added six times. If you want to use it as a special number and get it's value separately then you'll have to add it to the sum before the loop.
You should compare every new even number to the previous greatest even number and hence set the value of evenMax. You are comparing them to the firstNum so if the first number is 2 and the last even number is anything greater than two, it would be set as the value of evenMax. Compare every even number to the current maximum even number i.e current value of evenMax.
You don't check if the first number is evenor not and assign it to even max. So if it is 999999 it still get's assigned, but it is not even.
Please check it as correct answer and vote up if you find it useful.