Java, Program is suppose to determine integer of odd - java

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

Related

Looping with conditional statement

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();

How do I get the rightmost digits for step 1? Then how do I get the digits that weren't included for step 2?

import java.util.Scanner;
public class Ass. {
public static void main(String[] args) {
/*blanca 10/08/20
* 3.Following is a fun algorithm of three steps to check whether a given 8 digit number is acceptable.
* step1: starting from the rightmost digit,form the sum of every other digit.
* - For example the number is 12345658, this sum is 8+6+4+2 = 20.
* step2: double each of the digits that were not included in the preceding step; add all digits of the resulting number.
* - For the example number above,doubled digits would be 10,10,6,2. Adding those digits will yield (1+0+1+0+6+2)10.
* step3: Add the sum of the numbers in step1 and step2. if the last digit of that number is 0, the number is acceptable, not otherwise.
* Your program should read an 8 digit number and output whether it is acceptable or not.
*/
//declare
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int digits = 0;
Scanner data = new Scanner(System.in);
System.out.println("Enter a card number");
digits = data.nextInt();
//step 1
sum1 = digits%10;
// step 2
sum2 = digits%100;
//step 3
sum3 = sum1 + sum2;
if (sum3 = 0){
System.out.println("Acceptable");
}
else
{
System.out.println("Unacceptable");
}
I saw some other questions and saw that the place value (like %10) is suppose to give the digits but I don't know how to change it depending on the question?
Here are some suggestions.
To get the least significant digit, you use the remainder operator (%) with 10.
To get the next digit, you divide the original number by 10 and apply the remainder operator to the quotient.
For every other digit you need to apply the remainder operator and the division operator after multiplying the digit by 2. So 14 would be 1 + 4 which you should be able to figure out just like above.
You can either continue this until your starting number is 0. Or repeat in a loop 4 times, getting two digits per loop and performing the appropriate summing operations.
When done you simply test the result for the desired value.

Why doesn't the scanner class recognize the other numbers?

public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.

Java programming: How do I make this for loop program that accepts user input subtract the input properly?

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.

Find the even sum and even max

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.

Categories

Resources