reversing a number using do-while - java

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:

Related

Separating the Digits in an Integer - exercise from Deitel's Java book

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

decimal to binary output is incorrect

I can only get correct output for decimal less than five. the output for five is 110 when it should be 101. the output for six is 101 and the output for ten is 1100.
//while loop divides each digit
while (decimal > 0)
{
//divides and digit becomes the remainder
int digit = decimal % 2;
//makes the digit into a string builder so it can be reversed
binaryresult.append(digit);
decimal = decimal / 2;
display.setText(binaryresult.reverse());
}
Usee the below code it may work for you
import java.util.Scanner;
public class decToBinary{
public String decToBin(int n) {
StringBuilder result = new StringBuilder();
int i = 0;
int b[] = new int[10];
while (n != 0) {
i++;
b[i] = n % 2;
n = n / 2;
}
for (int j = i; j > 0; j--) {
result.append(b[j]);
}
return result.toString();
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal no :");
int n=sc.nextInt();
System.out.println("binary numbers is :");
decToBinary dtb = new decToBinary();
System.out.println(dtb.decToBin(n));
}
}
Something like this may be closer to what you are asking for:
while (decimal > 0) {
result.insert(0, (char) ((decimal % 2) + '0'));
decimal /= 2;
}
It uses insert to avoid reversing and adds the character instead of the number.
But you would be better off using a built in mechanism such as:
BigInteger.valueOf(decimal).toString(2)
i am not able to reproduce the behaviour using the following:
public static String decToBin(int n) {
StringBuilder result = new StringBuilder();
while (n > 0) {
int dec = n % 2;
result.append(dec);
n = n / 2;
}
return result.reverse().toString();
}
however, consider using the build-in
public static String decToBin(int n) {
return Integer.toBinaryString(n);
}
(or even BigInteger as stated above)
try this code , i hope this is what u r looking for:
public class DecimalToBinary {
public static void main(String[] args)
{
int decimal=11;
StringBuffer binaryValue=new StringBuffer();
while(decimal>0 ){
int rem=decimal%2;
decimal=decimal/2;
System.out.println("Remainder:"+rem);
binaryValue.append(rem);
}
System.out.println("binary is:"+binaryValue.reverse());
}
}

Why will my number to Binary converter only return the number 1?

I have created a converter which will hopefully convert any normal number which is inputted into a binary number, but it will only return the number "1" no matter what you input, why?
import java.util.Scanner;
public class NumtoBinary{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Number to binary converter");
int Num = sc.nextInt();
System.out.println(toBin(2));
}
public static int toBin(int Num){
int result = 0;
while(Num > 0){
int mod = Num % 2;
result = result * 1 + mod;
Num /= 2;
}
return result;
}
}
Your approach is close but for each iteration that produces zero for the mod you need to reflect that. You could use a String to track the result of each iteration and convert it to an integer for the return value like this:
public static int toBin(int Num) {
String result = "";
while (Num > 0) {
int mod = Num % 2;
result = mod + result;
Num /= 2;
}
return Integer.parseInt(result);
}
For example the method above if you input 12 then each iteration would build the string like this "0", "00", "100", "1100"

Java Palindrome and Reverse Order Integer

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).

Display Prime Factors Prompting User for Integer Using StackOfIntegers Java Class

So I have this assignment and I have been struggling any help or feedback would be welcomed :)
Problem
(Displaying the prime factors) Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. Using StackOfIntergers Class.
Here's what I have so far and the program compiles and runs but getting prime numbers instead of the prime factors.
package primefactors;
import java.util.Scanner;
public class PrimeFactors {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
final int number = scanner.nextInt();
int count = 0;
StackOfIntegers stack = new StackOfIntegers();
// Repeatedly find prime factors
for (int i = 2; i <= number; i++)
if (isPrime(i)) {
stack.push(i);
count++; // Increase the prime number count
}
// Print the prime factors
System.out.println("The prime numbers are \n");
final int NUMBER_PER_LINE = 10;
while (!stack.empty()) {
System.out.print(stack.pop() + " ");
if (stack.getSize() % NUMBER_PER_LINE == 0)
System.out.println(); // advance to the new line
}
}
public static boolean isPrime(int number) {
// Assume the number is prime
boolean isPrime = true;
for (int divisor = 2; divisor <= number / 2; divisor++) {
//If true, the number is not prime
if (number % divisor == 0) {
// Set isPrime to false, if the number is not prime
isPrime = false;
break; // Exit the for loop
}
}
return isPrime;
}
}
*Update#2*
So I needed to just get the prime factor working so this is what I ended up with after researching some more & coding.
It works. Now I need to work on having the program show both prime factors and prime numbers in a nice list.
Thanks for the feedback & suggestions.
import java.text.MessageFormat;
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
StackOfIntegers stack = new StackOfIntegers();
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) continue;
stack.push(i);
count++;
}
System.out.println("The prime factors are \n");
final int NUMBER_PER_LINE = 10;
while (!stack.empty()) {
System.out.print(MessageFormat.format("{0} ", stack.pop()));
if (stack.getSize() % NUMBER_PER_LINE == 0)
System.out.println(); // advance to the new line
}
}
}
StackOfInterger Class
public class StackOfIntegers {
private int[] elements;
private int size;
/** Construct a stack with the default capacity 16 */
public StackOfIntegers() {
this(16);
}
/** Construct a stack with the specified maximum capacity */
public StackOfIntegers(int capacity) {
elements = new int[capacity];
}
/** Push a new integer into the top of the stack */
public int push(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
return elements[size++] = value;
}
/** Return and remove the top element from the stack */
public int pop() {
return elements[--size];
}
/** Return the top element from the stack */
public int peek() {
return elements[size - 1];
}
//whether the stack is empty */
public boolean empty() {
return size == 0;
}
/** Return the number of elements in the stack */
public int getSize() {
return size;
}
}
This works as described. When I ran it with 20, I got the following output:
19 17 13 11 7 5 3 2
These are all prime numbers. I'm not sure why you expect 5,3,2,2.
I believe the next step is to go through all of these prime numbers and see if they are prime factors of 20. This should be 5 and 2. To do this, you should iterate over the list and see if the input % (which is modulus) the number you're testing is equal to 0.
Try this it returns the 5 smallest prime factors of a given number if there is 5 prime factors. If you wanted to display two lists, one for primes and one for prime factors why not create two stacks and display separatly.
public class Temp2 {
public static void main(String[] args)
{
int number, integer, count = 0;
StackOfIntegers stack = new StackOfIntegers();
Scanner input = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
integer = input.nextInt();
//Find prime factors
for (number = 2; number < integer; number++)
{
if (isPrime(number) && integer % number == 0)
{
stack.push(number);
count++;
if(count == 5) break;
}
}
// Print the smallest prime factors in decreasing order
System.out.println("The smallest prime factors of " + integer + " are ");
while (!stack.empty())
{
System.out.print(stack.pop() + ", ");
}
System.out.println(); //Advance to the new line
}//ENDMAIN
public static boolean isPrime(int number)
{
for (int divisor = 2; divisor <= number / 2; divisor++)
{
//If true, the number is not prime, return false
if (number % divisor == 0)
return false;
}
return true;
}
}//ENDCLASS
A workable solution for this assignment question can be found here:
http://www.besteduweb.com/assignment-solution-using-stack-of-integers-class.html
This is the 100% workable solution and works for me.
Recommended 100%.

Categories

Resources