Exercise from Deitel's "Java How To Program" 10th edition:
2.30 (Separating the Digits in an Integer) Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print
4 2 3 3 9
Assume that the user enters the correct number of digits. What happens when you enter a number with more than five digits? What happens when you enter a number with fewer than five digits?[Hint: It's possible to do this exercise with the techniques you learned in this chapter. You'll need to use both division and reminder operations to "pick off" each digit.]
Could someone explain to me how should I go about "picking off" individual integers using division and reminder operators?
EDIT: control structures (if / else and the like) are not allowed yet, those are explored in future chapters. Variables, arithmetic operators and comparison operators only.
You know that the number is 5 digit long.
What about
number / 10 000 to retrieve the first digit.
number = reminder
number / 1000 to retrieve the second digit.
number = reminder
number / 100 to retrieve the third digit.
number = reminder
number / 10 to retrieve the fourth digit.
and reminder is the 5th one.
Here is the answer of displaying digit in same order u have enter
import java.util.Scanner;
public class oddMethod {
public static void main(String[] args) {
System.out.println("Enter start number:");
int number=getNumber();
int last=Reverse1stTime(number);
System.out.println("Digit You Enter:"+last);
}
private static int getNumber() {
Scanner sr = new Scanner(System.in);
return sr.nextInt();
}
private static int Reverse1stTime(int number)
{ int digit=0;
int reverse=0;
while(number>0)
{
digit=number%10;
reverse=reverse*10+digit;
number=number/10;
}
return reverseAgain(reverse);
}
private static int reverseAgain(int number)
{ int digit=0;
int reverse=0;
while(number>0)
{
digit=number%10;
System.out.println(digit);
reverse=(reverse*10+digit);
number=number/10;
}
return reverse;
}
}
Input 12345
Output 12345
my small hint with division - you can divide by 10 and take a look, what is that operation giving...
More, you have to deduce if you want to learn programming.
I also just started with java and with this book, and this is the code that did the tric for me. Forgive me if i did something strange... :)
import java.util.Scanner;
public class SeparateNumber
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nr, nr1, nr2, nr3, nr4, nr5;
System.out.print("Enter a number with 5 digits: ");
nr = in.nextInt();
nr1 = nr / 10000;
nr2 = (nr % 10000) / 1000;
nr3 = ((nr % 10000) % 1000) / 100;
nr4 = (((nr % 10000) % 1000) % 100) / 10;
nr5 = (((nr % 10000) % 1000) % 100) % 10;
System.out.printf("%d%s%d%s%d%s%d%s%d%n", nr1, " ", nr2, " ", nr3, " ", nr4, " ", nr5);
}
}
Try this:
import java.util.*;
public class DigitsDisplay
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int digit;
System.out.print("Enter a positive number: ");
digit = input.nextInt();
int power = 1;
while (power <= digit) {
power *= 10;
}
power /= 10;
while (power > 0) {
System.out.println(digit/power);
digit %= power;
power /= 10;
}
}
}
Try something like this
String str1 = "";
int a = 12345;
while(a>0)
{
int b = a%10;
str1 = str1 + String.valueOf(b+" ");
a = a/10;
}
StringBuilder str = new StringBuilder(str1);
System.out.println(str.reverse());
Below code handles splitting on any int in integer range.
Steps:
Convert int to String
Convert each character of String to int by using Integer.parseInt
Store int digits in int[]
Print int[]
Sample code:
import java.util.*;
public class SplitDigits{
public static void main(String args[]) throws Exception {
System.out.println("Enter number:");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println("You have entered:"+number);
String str = String.valueOf(number);
int length = str.length();
if ( length > 0){
int[] digits = new int[length];
for ( int i=0; i < length; i++){
digits[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
}
for ( int i=0; i < digits.length; i++){
System.out.println("Digits:"+digits[i]);
}
}
}
}
output:
java SplitDigits
Enter number:
123456789
You have entered:123456789
Digits:1
Digits:2
Digits:3
Digits:4
Digits:5
Digits:6
Digits:7
Digits:8
Digits:9
import java.util.Scanner;
public class DigitSeparator{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 5 digit number: ");
int number = input.nextInt();
System.out.print((number / 10000)+ " ");
int divider = 10000;
int mod = number % 10000;
for(int i = 1; i <= 4; i++){
divider /= 10;
System.out.print( mod/divider +" ");
mod %= divider;
}
System.out.println();
}
}
first import java.util.Scanner; berfore your
class.
and write this code in your main method.
Scanner input = new Scanner(System.in);
System.out.print("Enter a five digit number: ");
int number = input.nextInt();
int first_digit = number / 10000;
int second_digit = (number % 10000) / 1000 ;
int third_digit = (number % 1000) / 100;
int fourth_digit = (number % 100) / 10;
int fifth_digit = (number % 10);
System.out.printf("%d %d %d %d
%d%n", first_digit, second_digit, third_digit, fourth_digit, fifth_digit);
package chapter1;
import java.util.Scanner;
public class Exercise3 {
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a number that consist of 5 digits: ");
int num =scan.nextInt();
int digit1 =num / 10000;
int digit2 =(( num % 10000) / 1000 ); // the modulus answer of num/10000 is divided by 1000
int digit3 =( ( num % 1000) / 100 );
int digit4 = ( ( num% 100 ) / 10 );
int digit5 = ( num % 10);
System.out.print (digit1+"\t");
System.out.print(digit2+"\t");
System.out.print(digit3+"\t");
System.out.print(digit4+"\t");
System.out.println(digit5+"\t");
}
}
Answer is:
//your package name
import java.util.Scanner; //for input the userin
public class SeperateDigit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("Enter a 5 digit number: ");
int number = input.nextInt();
int number1 = number/100000;
int arrange = number%10000;
int number2 = arrange/1000;
int number3 = (arrange % 1000) /100;
int number4 =(( arrange % 1000) % 100) / 10;
int number5 = ((arrange % 1000) % 100) % 10;
System.out.printf("%d %d %d %d %d", number1,number2,number3,number4, number5);
}
}
and Result is
Enter a 5 digit number: 422339
4 2 3 3 9
Related
I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)
Create a java program that reads an integer number (NUM) and determine its reverse by using the division and remainder/modulo operators. If the last digit is zero, replace it with a one(1) before reversing the number. Output also the sum of all the digits.
import java.util.*;
public class Main {
static int replace(int number){
if (number == 0)
return 0;
int digit = number % 10;
if (digit == 0)
digit = 1;
return (number/10) * 10 + digit;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
System.out.println("replace:"+replace(number));
int a, m = 0, sum = 0;
do{
a = replace(number) % 10;
m = m * 10 + a;
sum = sum + a;
number = replace(number) / 10;
}
while( replace(number) > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Currently the problem occurs in reversing the number because it also replace the last digit of the number, this should not happen.
Input/Output of current program
Enter the number : 2300
replace:2301
Reverse:1132
Sum of digits:7
do this instead
import java.util.*;
public class Main {
static int replace(int number){
if (number %10 == 0)
return number += 1;
return number;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
int a = 0, m = 0, sum = 0;
number = replace(number);
System.out.println("replace:" + number);
do{
a = number % 10;
m = m * 10 + a;
sum = sum + a;
number /= 10;
}
while( number > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Your code is fundamentally wrong because of the way you are replacing your numbers.
Changes made:
Changed replacing algorithm (You cannot change all 0 values to 1 that is wrong and why you got the wrong values)
Replace the number before you enter the loop. (You don't need to replace every iteration of the loop at 3 different place)
Expected output:
I have tried this program many times I didn't get the proper output till now please help me to solve this type of program.
input:n=3
output: 001 to 999
input:n=4
output:0001 to 9999
input:n=2
output:01 to 99
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int sum=1,result=0;
while(number!=0)
{
result=result+(9*sum);
sum=sum*10;
number--;
}
System.out.println(result);
for(int i=1;i<=result;i++)
{
System.out.printf("%02d ",i);//here i manually mentioned the %02d but i want to take user input
}
}
You can use this code
int number = 3;
String mask = "%0" + (number) + "d%n";
int max = (int)Math.pow(10, number)-1;
for (int x = 1; x <= max; x++)
System.out.printf(mask, x);
thanks to #RalfRenz
Can you try below code ?
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
String masked = "%0" + (num) + "d%n";
int max = (int)Math.pow(10, num)-1;
for (int k = 1; k <= max; k++)
System.out.printf(masked, k);
}}
Im having trouble in the reverse order section of my code. I'm storing the values in hund, tens, ones, etc. How do I pass the data back to the main method so as to display these numbers in reverse order?
import java.util.Scanner;
public class PP53v2 {
public static void main(String[] args) {
int leftOver = 0;
int number = 0;
int num1;
Scanner input = new Scanner(System.in);
System.out.println("Hit #1 to reverse a number. Hit #2 to return if its a palindrome.");
int selection = input.nextInt();
switch(selection) {
//problem 1
case 1:
System.out.println("Enter a number to be displayed in reverse order.");
System.out.println("For accuracy, this must be a five digit number.");
number = input.nextInt();
num1 = reverse(number);
System.out.print(num1);
break;
//problem 2
case 2:
System.out.println("Enter an integer to see if it's a palindrome.");
System.out.println("For accuracy, this must be a five digit number. (I.E. 12321 is a palindrome)");
number = input.nextInt();
if (isPalindrome(number)) {
System.out.println("The number is a palindrome." + number);
} else
System.out.println("The number isn't a palindrome." + number);
break;
}//switch end
}//main end
public static int reverse(int number) {
String leftOver = 0;
int remaining =0;
int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds
while (number > 0) {
tenThou = number / 10000;
thou = number % 10000 / 1000;
tens = number % 100 /10;
ones = number % 10;
//remaining = number % 10;
//number = number / 10;
//leftOver = leftOver + remaining;
}//end while
return leftOver;
}// reverse method end
public static boolean isPalindrome(int number) {
int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds
tenThou = number / 10000;
thou = number % 10000 / 1000;
tens = number % 100 /10;
ones = number % 10;
if (tenThou == ones && thou == tens)
return true;
else
return false;
}//method end
}//class end
Use this logic
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
n is the integer(your input).
I am trying to limit the input number to be greater than 0 and an integer.
Code Here:
import java.util.Scanner;
public class PROB4_CHAL1 // Sum of Numbers
{
public static void main(String[] args)
{
int sum = 0;
int count = 1;
int number = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
while (number >= count)
{
sum += count;
count ++;
}
System.out.println("Sum equals " + sum);
}
}
New to Java so anything will help!
You can take the input in a while loop, like so:
int number = 0; // start at 0 so the while loop is true for the first time
while (number < 1) {
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
}
This way it will keep asking them to input a number until the number they input is greater than 0.