Print each digit of a number on a new line in Java - java

I have the following code written with the purpose of the program is for the user to input a number i.e. 123 and the program will output it as 1 2 3 vertically. No matter what I do, my program does it as 3 2 1. I need to use a loop in this program and I can't seem to figure it out.
import java.util.Scanner;
public class DigitsDisplay {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int a = getInt("Give a non-negative integer: ");
double backwards = 0;
int reverse;
int numOfDigits = numOfDigits(a);
double place = Math.pow(10, numOfDigits);
while (a != 0) {
reverse = a % 10;
backwards = backwards + place * reverse;
System.out.println(reverse);
a = a / 10;
}
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int numOfDigits(int a) {
int numOfD = (int)(Math.log10(a)) + 1;
return numOfD;
}
}

Reverse the reversed value
Your program is designed to reverse the digits. And it does. If you want to reverse them back, I suggest you append them to a StringBuilder and then reverse that. Like,
StringBuilder sb = new StringBuilder();
while (a != 0) {
reverse = a % 10;
sb.append(reverse).append(System.lineSeparator());
backwards = backwards + place * reverse;
a = a / 10;
}
System.out.print(sb.reverse());
Using a Regular Expression
Your algorithm could be simplified by using String.replaceAll(String, String) with a regular expression that matches and groups all digits of a and then replaces each digit with itself plus a new line. Something like,
int a = getInt("Give a non-negative integer: ");
System.out.println(String.valueOf(a).replaceAll("(\\d)",
"$1" + System.lineSeparator()));

Related

I was writing a code to enter a number and then reversing it, but the modulo isn't working it seems. What could have gone wrong here?

My concern is only with why the modulo (%) isn't working. Please don't comment on the code on it's entirety. My code is as displayed below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a number");
int num = scanner.nextInt();
int count = 0;
while(num!=0) {
num = num/10;
count++;
}
System.out.println("Total digits = " + count );
int rem = num % 10;
System.out.println(rem);
}}
The output is
Also quick note: the output for "rem" is 0 only when "num" is passed as an operand. If a number replaces the "num" then the code works just fine
There is a wrong logic used for reversing the number. You can try below code.
public class ReverseNumberExample1
{
public static void main(String[] args)
{
int number = 987654, reverse = 0;
while(number != 0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}

Java: String index out of range while checking if a number is a palindrome

So, in order to check if a number is a palindrome I converted it to a string. I know there is a similar question on SO but I have already checked that solution, so any help would be appreciated.
Why do I get a "Exception in thread "main" java.lang.NumberFormatException: ?
My code is here;
/*
(Palindrome integer) Write the methods with the following headers
// Return the reversal of an integer, i.e., reverse(456) returns 654
public static int reverse(int number)
// Return true if number is a palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome
if its reversal is the same as itself. Write a test program that prompts the
user to enter an integer and reports whether the integer is a palindrome.
*/
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
if (isPalindrome(number))
System.out.println("The number is a palindrome");
else
System.out.println("The number is not a palindrome");
}
public static int reverse(int number) {
String reverse = "";
String n = number + " ";
for (int i = n.length() - 1; i >= 0; i--) {
reverse += n.charAt(i);
}
return Integer.parseInt(reverse);
}
public static boolean isPalindrome(int number) {
return number == reverse(number) ? true : false;
}
}
The problem is in the reverse function.
in fact the instruction String n = number + " "; is the concatenation of the value number with a blank string. This is not a number and later on gives NomberFormatException at the instruction return Integer.parseInt(reverse); . You should use String n = Integer.toString(number);
Here's the reviewed method
public static int reverse(int number) {
String reverse = "";
String n = Integer.toString(number); // + " ";
System.out.println(reverse);
for (int i = n.length() - 1; i >= 0; i--) {
reverse += n.charAt(i);
}
return Integer.parseInt(reverse);
}
You should change the line:
String n = number + " ";
for the following:
String n = Integer.toString(number);
Because you are trying to parse a String with a blank space as last character to an int, that is why it throws the NumberFormatException.

converting to decimal but without using integer.parseInt() method

So this is my first programming course and I have an assignment to convert a binary number entered by the user to a decimal. And my binary number should be stored in a a string.
And to check that all my digits are 1s and 0s I need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
So I did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert it?
So my question is: how can I write this code in another way that doesn't use this method?.
Here's my code:
import java.util.*;
import java.lang.*;
public class Assignment2
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int converttodecimal;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
converttodecimal = Integer.parseInt(st,2);// integer.parseInt(String , int radix);
System.out.println("the equivalent decimal value is: " +converttodecimal );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
}//end of class
This is the output:
enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53
Thank you in advance I already asked this question else where but I didn't get the answer I wanted.
UPDATE:
I wrote the program again based on your suggestions #akhil_mittal #fabian but if i want to write the converting method in the program itself (not calling the method) how can i do that ?
here's the code:
import java.util.*;
import java.lang.*;
public class Assignment2test
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int result;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
result = convertBinaryToDecimal(st);
System.out.println("the equivalent decimal value is: " + result );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int convertBinaryToDecimal(String st){
double decimal =0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)== '1'){
decimal = decimal + Math.pow(2,st.length()-1-i);
}
}
return (int) decimal;
}
}
//end of class
Do it manually, you can just multiply each digit for the corresponding power of two and sum the results.
Regarding the last part of your question, you can simply use java.lang.Math.pow(2,exponent), there is no specific operator for that if that was what you were wondering.
You can use the bit-shift operator to get powers of 2:
int pow2(int exponent) {
return 1 << exponent;
}
which should be more efficient than Math.pow.
But you could also calculate a binary number like this (example for 0b110101):
((((((1)*2+1)*2+0)*2+1)*2+0)*2+1)
i.e. by repeatedly multiplying by 2 and adding the next digit.
I have written two methods which use basic computation to convert binary to decimal, one takes long and other takes String. You can also use them to check the differences in implementation. The method is very simple and easy to understand.
public static int convertBinaryToDecimal(String binary){
double decimal =0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)== '1'){
decimal = decimal + Math.pow(2,binary.length()-1-i);
}
}
return (int) decimal;
}
public static int convertBinaryToDecimal(long numberInBinary){
int decimal = 0;
int power = 0;
while(true){
if(numberInBinary == 0){
break;
} else {
long temp = numberInBinary%10;
decimal += temp*Math.pow(2, power);
numberInBinary = numberInBinary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
int binaryNumber = 110011;
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumber));
String binaryNumberInString = "110011";
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumberInString));
}
If you want to ensure that String only contains 0 and 1 then you can try yourself and let me know if you need any help.
Binary to decimal Conversion without using Integer.parseInt method
public class BinaryDecimal
{
public static int binaryToDecimal(int binary) {
int decimal = 0;
for (int power = 1; binary > 0; power *= 2, binary /= 10)
decimal += power * (binary % 10);
return decimal;
}
public static void main(String a[]) {
System.out.println("11 ===> " + binaryToDecimal(11));
//System.out.println("11 ===> " + binaryToDecimal(Integer.parseInt(a[0]))); //Input from command line
}
}

binary to base10 in java with main method and TWO classes/method (boolean and

I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}

Print Palindrome in Java

I have the following code and i want to print the palindrome on console. Please let me know what should come inside the if condition so that it can print all palindrome in between 0 to 10000.
The palindrome is 161, 1221, 4554, etc....
Java code:
int palindrome[];
palindrome = new int[10000];
for (int count = 0; count < palindrome.length; count++ ){
palindrome[count] = 0;
if(){
System.out.println(count);
}
}
This will do:
if (isPalindrome(count)) {
System.out.println(count);
}
...
public boolean isPalindrome(int num) {
// implement method here (ie: do your homework)
}
Something like this might work
public boolean isPalindrome(final int num) {
final String s = Integer.toString(num);
return s.equals(new StringBuffer(s).reverse().toString());
}
You need to transform the number into a string and then check if the string reversed is equal to the original string. This looks a lot like some homework, if so please add the appropriate tag.
The code golf solution:
public static boolean isPalindrome(int number) {
return ("" + number).equals(new StringBuilder("" + number).reverse().toString());
}
You could also reverse the number and check if the reversed one and your number are equal.
To reverse the number: keep dividing it with 10 until the result is 0. Save the remainders of the divisions. Starting from the first remainder you get, multiply it by 10 and add the next remainder. Keep multiplying by 10 and adding remainders till you use all the remainders.
To revers I use a StringBuffer, StringBuffer(num).reverse().toString();
Here are some hints:
a) To get the last digit of a number use the remainder (%) operator
Example:
result = number % 10; // 21 % 10 = 1
b) To cut of the last digit, divide by 10
Example:
number = number / 10; // 21 / 10 = 2;
c) Multiply the result by 10
Example:
result = result * 10; // 1 * 10 = 10
d) Repeat until some condition is fulfilled (shouldn't be too hard to figure out ;-))
boolean isPalin(int n)
{
String s = Integer.toString(n);
return s.equals( new StringBuffer(s).reverse().toString() );
}
so your if condition should contain: isPalin(count)
boolean isPalin(int n)
{
int nn = 0, tmp = n;
while(n > 0)
{
nn = nn*10 + n%10;
n /= 10;
}
return tmp==nn;
}
I prefer doing it this way instead of using strings, since strings make the process slow as it involves a lot of overhead.
import java.util.*;
import java.io.*;
public class TestFinal {
public static Scanner c = new Scanner(System.in);
public static void main(String[] args) {
String original ,reverse ="";
// TODO, add your application code
System.out.println("Enter the text!");
original = c.next();
int length = original.length();
for(int i =length - 1;i >= 0;i--)
reverse = reverse +original.charAt(i);
if(original.equals(reverse))
System.out.println("entered strig is a palindrome");
else
System.out.println("the text is not a palindrome");
}
}
An easy way to print palindrome:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
/* Enter your code here. Print output to STDOUT. */
int len = A.length();
String B ="";
for(int i=len-1;i>=0;i--){
B=B+A.charAt(i);
}
if(A.equals(B))
System.out.println("Yes");
else
System.out.println("No");
}
}

Categories

Resources