How to read each individual digit of a number in Java - java

I am trying to run a program that outputs the sum of every digit of an entered in integer. How would I go about reading the number and outputting each digit?
Example: Input is 4053 the output would be "4+0+5+3 = 12".
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
while (num > 0) {
int lastDigit = num % 10;
sum = sum + lastDigit;
num = num/10;
}
}
}
That is the code I used for calculating the sum of the individual digits, now I just need help with outputting the individual digits. Any tips and tricks would be much appreciated.

import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
String numToString = "";
while (num > 0) {
int lastDigit = num % 10;
numToString +=lastDigit+" + ";
sum = sum + lastDigit;
num = num/10;
}
//eliminate the last + sign
numToString = numToString.substring(0,numToString.lastIndexOf("+")).trim();
System.out.println(numToString +" = " +sum);
}
}

I am not sure what you mean by outputting but instead of this you can read the number as string and take each character and parse it to integers
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
String number = stdin.next();
int[] result = new int[number.length];
for(int i=0;i<number.length;i++) {
result[i] = Integer.parseInt(number.charAt(i)+"");
}
return result;

You may read this like String and then divided by the number.
final Scanner s = new Scanner ( System.in );
final String line = s.nextLine ().trim ();
final char [] array = line.toCharArray ();
int sum = 0;
for ( final char c : array )
{
if ( !Character.isDigit ( c ) )
{
throw new IllegalArgumentException ();
}
sum = sum + Character.getNumericValue ( c );
}
System.out.println ( "sum = " + sum );

without a scanner you can do
StringBuilder sb = new StringBuilder();
String sep = "";
int ch;
long sum = 0;
while((ch = System.in.read()) > ' ') {
if (ch < '0' || ch > '9') {
System.out.println("Skipping " + (char) ch);
continue;
}
sb.append(sep).append((char) ch);
sep = " + ";
sum += ch - '0';
}
sb.append(" = ").append(sum);
System.out.println(sb);

Try this:
import java.util.*;
public class Digits {
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter number -> ");
int number = input.nextInt();
int sum = 0;
String numStr = "" + number;
while(number > 0)
{
int lastDigit = number % 10;
sum += lastDigit;
number = number / 10;
}
for(int i = 0; i < numStr.length();i++)
{
System.out.print(numStr.charAt(i));
// Dont print an extra + operator at the end
if( i == numStr.length() - 1) continue;
else
System.out.print(" + ");
}
System.out.print(" = " + sum);
}
}

Related

I am trying to write a program that allows me to input multiple integers, but it won't allow me to enter in my set of integers

My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}

How to reverse a number in Java accepted by user and add both reversed number

I have written a code to reverse a number in java. But its taking only one character/displaying it.
import java.util.Scanner;
class HelloWorld
{
public static void main(String args[])
{
int n,n1, reverse = 0,rev = 0;
System.out.println("Enter the number to reverse");
Scanner scanner = new Scanner(System.in);
System.err.println("Please enter first number to reverse : ");
int number = scanner.nextInt();
System.out.println("Enter second number to reverse :");
int num = scanner.nextInt();
if( number >0)
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
if(num>0)
{
rev = rev * 10;
rev = rev + num%10;
num = num/10;
}
}
System.out.println("Reverse of entered number is "+reverse);
System.out.println("Reverse of entered number is "+rev);
}
}
Input1 -65
output displayed - 5
Input2 -34
output displayed - 4
I have to reverse the user accpeted inputs and add the reverse of both boths inputs.
1)Use while instead of if.
2) If you compute the reverse of second number inside the while loop that finds the reverse of first number, if second number is longer then it won't work. Do it separately
while(number > 0)
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
while(num > 0)
{
rev = rev * 10;
rev = rev + num%10;
num = num/10;
}
you can do it like this , as #user7 pointed out, use an while loop , instead of if loop
while( number >0)
{
reverse1 = reverse1 * 10;
reverse1 = reverse1 + number%10;
number = number/10;
}
while( number2 >0)
{
reverse2 = reverse2 * 10;
reverse2 = reverse2 + num%10;
num = num/10;
}
System.out.println(reverse1+reverse2);
now for multiple Numbers
int[] numbers= numbers to be reversed;
reverseSum=0;
for(int i=0;i<numbers.length;i++){
reverseSum+= reverse(numbers[i]);
}
...
public int reverse(int number){
while( number >0)
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
return reverse;
}
hope this helps!
Good luck!
You can do
import java.util.Scanner;
import java.lang.StringBuilder
class HelloWorld
{
public static void main(String args[])
{
int n,n1, reverse = 0,rev = 0;
String string1,string2;
System.out.println("Enter the number to reverse");
Scanner scanner = new Scanner(System.in);
System.err.println("Please enter first number to reverse : ");
int number = scanner.nextInt();
System.out.println("Enter second number to reverse :");
int num = scanner.nextInt();
StringBuilder str1 =new StringBuilder(number+"");
StringBuilder str2 =new StringBuilder(num+"");
string1=str1.reverse().toString();
string2=str2.reverse().toString();
}
System.out.println("Reverse of entered number is "+string1);
System.out.println("Reverse of entered number is "+string2);
}
}
At last you can conver the reversed string to integer using Integer.ParseInt method and add it

JAVA Display how many ODD and EVEN numbers using only one counter?

I have a program here in java that asks the user to input ten integer numbers and would print out how many are ODD and how many are EVEN.
import java.io.*;
public class Count {
public static void main(String[] args) {
int i, , even_ctr=0, odd_ctr = 0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++; //counter for even
if(n % 2 == 0)
odd_ctr++; //counter for odd
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ odd_ctr);
}
}
I am trying to change the program by using only one counter instead of two counter. Anyone knows how?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
int i,n, even_ctr=0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++;
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ (10-even_ctr));
}
}
Just keep the first counter incrementing for ODD number detection (OR EVEN but either of them). At the end of the computation, if ODD counter = 4, and total number of numbers entered are 10, then 10 - ODDcounter = 10 - 4 = 6 are the number of even numbers.
For this it looks like it would be equally useful to use the Scanner so that you can avoid the step of having to parse the string.This also would require you to import java.util.Scanner but you can use the scanner to take in strings or integers.
Scanner in = new Scanner(System.in);
int input;
int evenCount = 0;
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.nextInt();
}catch(IOException e){
System.out.println("Error!");
}
if(input % 2 == 0)
evenCount++;
}
System.out.println("EVEN: " + evenCounter + "\nODD: "+ (10 - evenCounter);
Include in.close(); at the end of the method to close the scanner or the reader which ever you use.
package evenoddten;
import java.util.Scanner;
public class EvenOddTen {
public static void main(String[] args) {
int num1 = 0, num2, even = 0, count = 0;
Scanner scr = new Scanner(System.in);
System.out.print("Total Nos:");
num2 = scr.nextInt();
while(count<num2) {
System.out.println("Enter no:");
num1 = scr.nextInt();
if (num1%2 == 0) {
even = even + 1;
}
count = count+1;
}
System.out.println("Even nos are:"+even);
System.out.println("Odd nos are:"+(count - even));
}
}

How to convert octal to decimal in the different form without using APIs?

I tried to convert octal to decimal and I got some output but I am not satisfied with it. Can anyone give an idea how to convert a different model without using API-s?
public static void main(String args[]){
System.out.print("Enter the number to convert");
Scanner ss =new Scanner(System.in);
int a = ss.nextInt();
int b = ss.nextInt();
int c = ss.nextInt();
int d = ss.nextInt();
int temp =(a*(8*8*8));
int temp1 =(b*(8*8));
int temp2 =(c*(8));
int temp3 =(d*(1));
System.out.println("The decimal is " +"\n" + (temp +temp1 +temp2 +temp3))
}
Try this one:
public static void main(String[] args)throws IOException
{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String oct = reader.readLine();
int i= Integer.parseInt(oct,8);
System.out.println("Decimal:=" + i);
}
I havn't try this but try to get a logic,
take input in a string then
String s ; //for input
String answer ="";
for(a=0,b=s.length-1;b>=0;b--)
{
int digit =Integer.parseInt(s.charAt(a));
int ans = (int)(digit * Math.pow(8,b));
answer+=ans;
a++;
}
Maybe my version is something you are looking for:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
String numberString = sc.nextLine();
int[] eachNumbers = new int[numberString.length()];
for(int i = 0; i < eachNumbers.length; i++){
eachNumbers[i] = Integer.parseInt(numberString.substring(i, i+1));
}
int digit = 0;
for(int i = 0; i < eachNumbers.length; i++){
if(eachNumbers.length > 1){
digit += (eachNumbers[i] * Math.pow(8, eachNumbers.length - (i+1)));
}else{
digit += (eachNumbers[i] * 1);
}
}
System.out.println("The Octal " + numberString + " as Decimal is " + digit);
}
I know there is alot that can be made better but I'm still learning and wanted to help you :)

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

Categories