print the nth digit of a number in JAVA - java

I want to print nth digit of a number (from left to right) in JAVA. Here's what I've tried, I'm a total noob.
public class NewClass {
public static void main(String args[]) {
System.out.println("enter number: ");
Scanner s = new Scanner(System.in);
int number = s.nextInt();
System.out.println("enter n: ");
Scanner n = new Scanner(System.in);
int num = n.nextInt();
for (int i = 1; i <= num; i++) {
number = number / 10;
};
System.out.println("The nth Digit = " + number);
}

Following #ryan 's explanation, I found a solve in my way.
package com.mycompany.lab;
import java.util.Scanner;
int reversed = 0, digit;
System.out.println("enter number: ");
Scanner s=new Scanner(System.in);
int number=s.nextInt();
while(number != 0) {
// get last digit from num
digit = number % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
number /= 10;
}
System.out.println("enter n: ");
Scanner n=new Scanner(System.in);
int num=n.nextInt();
for(int i=1;i<num;i++){
reversed = reversed / 10;
};
while(reversed > 10){
reversed = reversed % 10;
}
System.out.println("The nth Digit = " + reversed);
}
}

Related

Adding 2 integers in 1 User input

I want to make the user input 2 integers in 1 input like this
Enter two integers: 2 2 // sum = 4
Here is my sample code:
Scanner s = new Scanner(System.in);
int x, num1, num2, sum;
System.out.print("*Enter 2 integer: ");
x = s.nextInt();
int sum = num1 + num2;
System.out.println(" Sum = "+ sum);
Is it possible to add 2 integers without using variables num1 and num2?
I want the output to be like this.
Enter two integers: 2 2
sum = 4
Add any number of integers:
Scanner s = new Scanner(System.in);
System.out.print("Enter some integers: ");
int sum = 0;
while (s.hasNextInt()) {
sum += s.nextInt();
}
System.out.println(" Sum = " + sum);
Case 1:
If you have only 2 values then follow the below code
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter 2 integer: ");
for(int i = 0; i < 2; i++)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}
Case 2:
If you have some More than 2 numbers but you have an idea about how many numbers to sum then follow the below code.
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter how many integers to sum: ");
int iterate = scan.nextInt();
System.out.print("*Enter " + iterate + " integer: ");
while(iterate-- > 0)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}

Why isn't my for loop that assigns values to arrays working?

I'm expecting the program to output all the digits entered, but it is only outputting the last digit in the number over and over again.
import java.util.Scanner;
public class Example9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//asks user to input the first 9 digits of an ISBN
System.out.println("Enter first nine digits: ");
int firstNine = input.nextInt();
int[] digits = new int[9];
int digitsLeft = firstNine;
for(int i = digits.length - 1; i > 0; i--) {
int digit = firstNine % 10;
digitsLeft = (int) Math.floor(digitsLeft / 10);
digits[i] = digit;
System.out.println(digits[i]);
}
}
}
int digit = firstNine % 10;
must be
int digit = digitsLeft % 10;
Also, with i > 0 you will not add the first digit. It must be i >= 0.

Create a java application that displays the sum of the digits of a number

I am relatively new to Java and I'm currently learning while, do while and for loops. I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how. I previously created an application that displayed ONLY THE DIGITS of a number. Here it is.
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
}
I'm trying to think of a possible way to expand on this program, but I have no idea why. Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops. Thank you!
not much code has to be added for summing the digits :
First solution : using a substract with '0' character
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + (sdigit.charAt(i) - '0');
}
System.out.println("Sum is : "+sum);
Second solution : using Integer.parseInt which converts String to int :
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}
System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());
int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
currDigit = number % 10; //fetching last digit
System.out.println(currDigit);
sum = sum + currDigit;
number = number / 10;
}

How to display individual digits of integer input?

I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);

control structure, repetition exercise: How to get the sum of the digits of a number?

Guys can you please help me answer this exercise using for loop without using string methods.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);

Categories