How to sum the digits of two integers? - java

How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);

public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9

You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}

//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}

Related

Java decimal to binary error in conversion

I'm doing a number systems code right now and on my decimalToBinary, whenever I enter a decimal number it always converts it to a 1 no matter what decimal number it is. The code is down here.
public static void decimalToBinary() {
do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();
if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}
} while (numDecimal < 0);
int intNum = Integer.valueOf(numDecimal);
int counter = 0;
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
for (int i = counter-1; i >= 0; i--) {
System.out.println("Your binary number is " + binaryVal[i]);
}
}
You missed a loop while doing the conversion. below is the working code
public static void decimalToBinary() {
int numDecimal = 0;
Scanner input = new Scanner(System.in);
int[] binaryVal = new int[100];
do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();
if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}
} while (numDecimal < 0);
int intNum = Integer.valueOf(numDecimal);
int counter = 0;
while(intNum >0){
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
System.out.println("Your binary number is :");
for (int i = counter-1; i >= 0; i--) {
System.out.print("" + binaryVal[i]);
}
input.close();
}
I recommend you to change the code by the following snippet, you also need to consider to create binaryVal array with a sufficient dimension in order to hold the complete number digits that it is going to generate the transformation to binary.
do {
binaryVal[counter++] = intNum % 2;
intNum = intNum / 2;
} while (intNum > 0);
for (int i = counter - 1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
If you are learning programming you can do as follows
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int intNum;
while ((intNum = scanner.nextInt()) > 0) {
decimalToBinary(intNum);
System.out.println();
}
}
public static void decimalToBinary(int intNum) {
int counter = 0;
int[] binary = new int[31];
while (intNum > 0) {
binary[counter++] = intNum % 2;
intNum = intNum / 2;
}
for (int i = counter - 1; i >= 0; i--) {
System.out.print(binary[i]);
}
}
}
Off course there are more optimized solution.
But if for other purpose you can simply do
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int intNum;
while ((intNum = scanner.nextInt()) > 0) {
String binary = Integer.toBinaryString(intNum);
System.out.println(binary);
}
}

Varied amounts of input data

Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
10 20
You can assume that at least one non-negative integer is input.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average?
Also, is this this the most efficient way I could have done it?
How about this? If you have questions from the implementation, please ask.
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
If you use while loop instead of do-while loop, you don't have to count the negative number input anymore. And no, it's not the most efficient way, but it's a good start!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}

count all numbers in range having a specific digit

I want to count how many numbers have digit number 4 in a range of numbers
e.g 1-100 count all numbers having digit number
i.e 4,14,24,34,40,41,42,43,44,45,46,47,48,49,54,64,74,84 and 94 total 19 numbers
I am having problems with counting number of integers with digit 4 in them please help!!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0;
while (true) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
while (num != 0) {
int i = num % 10;
if (i == 4) {
count++;
break;
}
num = num / 10;
}
}
System.out.println(count);
}
else
break;
}
}
}
To check if a number contains a specific digit or not, here is a trick you can use :
Convert both number and digit to String and use String::contains (Simple)
Here is a piece of code you can use If you are using Java 8 :
int number = 4, min = 0, max = 100;
String numberToString = String.valueOf(number);
long count = IntStream.rangeClosed(min, max) //Range of numbers between min and max
.filter(n -> String.valueOf(n).contains(numberToString)) // Use the filter
.count();// Then count the result
System.out.println(count); // 19
//a few changes were needed into your code.. here is the solution...
public class MaxOccurance {
public static void main(String[] args) {
int count = 0;
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt(), temp;
if (num1 != 0 || num2 != 0) {
for (int num = num1; num <= num2; num++) {
temp = num;
while (temp != 0) {
int i = temp % 10;
if (i == 4) {
count++;
// break;
}
temp = temp / 10;
}
}
System.out.println(count);
}
}
}

Add the factors of a number

public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n = 0;
int g = 0;
int term = 0;
int temp = 0;
int sum = 0;
int factor = 1;
System.out.print("Input N:");
n = x.nextInt();
g = n;
if (n <= 0) {
System.out.println("Please enter a positive integer");
System.exit(0);
}
if (n > 0) {
System.out.print("The factors are:");
while (factor < n) {
if (n % factor == 0) {
System.out.print(factor + ",");
}
factor++;
}
}
}
If I input number 8, the factors are 1,2, and 4. What I am trying to achieve is to add the factors of 8 which are 1,2 and 4, which would result in 7.
import java.util.Scanner;
public class Demo {
public static void main(String[] args)
{
Scanner x=new Scanner(System.in);
int n=0;int g=0; int term=0;int temp=0;
int sum=0; int factor=1;
System.out.print("Input N:");
n=x.nextInt();
g=n;
int number = 0;
if (n<=0)
{
System.out.println("Please enter a positive integer");
System.exit(0);
}
if (n>0)
{
System.out.print("The factors are:");
while (factor<n)
{
if (n%factor==0)
{
System.out.println(factor+",");
number+=factor;
}
factor++;
}
}
System.out.println("Sum = "+number);
}
}
import static java.lang.System.*;
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner kb = new Scanner(in);
out.print("Enter a number: ");
int num = kb.nextInt();
int sum = 0;
int x = 1;
for(x = 1; x <= num; x++){
if (num % x == 0){
sum = sum + x;
}
}
out.print(sum);
}
}

Java program to find the largest & smallest number in n numbers without using arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 months ago.
Improve this question
I could get the largest without using arrays but, unable to get the smallest one.
public static void main(String[] args)
{
int smallest=0;
int large=0;
int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=0;i<n;i++)
{
num=input.nextInt();
if(num>large)
{
large=num;
}
System.out.println("the largest is:"+large);
//gives the largest number in n numbers
code for the smallest..
if(i==0&&num>0)
small=num;
if(num<small)
small=num;
System.out.println(small);
}
Try this :
int smallest = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
num=input.nextInt();
if(num>large)
{
large=num;
}
if(num<smallest){
smallest=num;
}
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
System.out.println("enter the number");//how many number you want to enter
Scanner input = new Scanner(System.in);
int n = input.nextInt();
num = input.nextInt();
smallest = num; //assume first entered number as small one
// i starts from 2 because we already took one num value
for (int i = 2; i < n; i++) {
num = input.nextInt();
//comparing each time entered number with large one
if (num > large) {
large = num;
}
//comparing each time entered number with smallest one
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
Try this...This simple
import java.util.Scanner;
class numbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct");
}
}
public class Main {
public static void main(String[] args) {
int i = 10;
int j = 20;
int k = 5;
int x = (i > j && i > k) ? i : (j > k) ? j : k;
int y = (i < j && i < k) ? i : (j < k) ? j : k;
System.out.println("Largetst Number : "+x);
System.out.println("Smallest Number : "+y);
}
}
Output:
Largetst Number : 20
Smallest Number : 5
Try the code mentioned below
public static void main(String[] args) {
int smallest=0; int large=0; int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
num=input.nextInt();
smallest = num;
for(int i=0;i<n-1;i++)
{
num=input.nextInt();
if(num<smallest)
{
smallest=num;
}
}
System.out.println("the smallest is:"+smallest);
}
#user3168844: try the below code:
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
import java.util.Scanner;
public class LargestSmallestNumbers {
private static Scanner input;
public static void main(String[] args) {
int count,items;
int newnum =0 ;
int highest=0;
int lowest =0;
input = new Scanner(System.in);
System.out.println("How many numbers you want to enter?");
items = input.nextInt();
System.out.println("Enter "+items+" numbers: ");
for (count=0; count<items; count++){
newnum = input.nextInt();
if (highest<newnum)
highest=newnum;
if (lowest==0)
lowest=newnum;
else if (newnum<=lowest)
lowest=newnum;
}
System.out.println("The highest number is "+highest);
System.out.println("The lowest number is "+lowest);
}
}

Categories