Coverting a decimal to binary using for loops? - java

I'm trying to write a program that converts decimal to binary and decimal to octal.
I can convert from decimal to binary, but from decimal to octal it just doesn't work.
import java.util.*;
public class RadixConversion
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scan.nextInt();
System.out.println("Convert to base: ");
String letter = scan.next();
if (letter.equals("b")||letter.equals("B"))
{
int remainder = 0;
for (int i = 1; number > 0; i++)
{
number /= 2;
remainder = number % 2;
System.out.print(remainder);
}
}
else if (letter.equals ("o") || letter.equals ("O"))
{
int remainder = 0;
for (int i = 1; number >0 ; i++)
{
number /= 8;
remainder = number % 8;
System.out.print(remainder);
}
}
}
}

This is a bit more complicated the way I learned it. You have to find the largest power of 8 that fits in the number, see how many times it goes into the number, and repeat the process with the next lowest power of 8. You print each digit as you go.

neither one looks to be generating the correct value, it would just be less obvious with 0's and 1's. You are dropping the first digit and printing the digits in reverse order (the one's digit get printed first)
int remainder = 0;
String result = "";
for (int i = 1; number >0 ; i++)
{
remainder = number % 8;
result = remainder + result; // remainder first puts the digits in the right order
number /= 8;
}
System.out.print(result);

Related

Armstrong Number Checker in Java

I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == 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.

Java program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive

Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);

Assign of user input number to array in char data type

I'm trying to ask the user to input a three digit number, then have the code assign a new variable to the char of each digit using charAt() and put each digit into an array. So far it allowed me to input a number, but then it stops and doesn't do anything else, so I think it is a problem with this part. How would you do that?
The purpose is so that the computer with generate a three digit number, ask the user to input a number, then analyze the numbers to see how many digits of the guessed number are the same as in the generated number and how many of the correct digits are in the correct place. So if the generated number is 180, and you guess 481, then the digits correct would be 2 and the places correct would be 1.
import java.util.Scanner;
public class Main {
public static void main(String[] args){
char[] array = new char [3];
for (int i = 0; i < array.length; i++){
array[i] = (char)(Math.random() * 9);
}
char[] guess = {0, 0, 0};
System.out.println("I have a three digit number with no repeating digits. Guess the number.");
while (guess != array){
Scanner input = new Scanner(System.in);
char number1 = input.next().charAt(0);
char number2 = input.next().charAt(1);
char number3 = input.next().charAt(2);
guess[0] = number1;
guess[1] = number2;
guess[2] = number3;
int digit = 0;
int place = 0;
for(int n = 0; n < array.length; n++){
for(int d = 0; d < array.length; d++){
if(array[n] == guess[d]){
digit++;
}
}
}
for(int r = 0; r < array.length; r++){
if(array[r] == guess[r]){
place++;
}
}
System.out.println("Correct digits: " + digit);
System.out.println("Correct places: " + place);
}
System.out.println("Congratulations, you got it");
}
}
Scanner input = new Scanner(System.in);
String num = input.next();
char number1 = num.charAt(0);
char number2 = num.charAt(1);
char number3 = num.charAt(2);
To fix the problems you'll run into after this:
array[i] = (char) (Math.random() * 9 + '0');
You need to store the character correctly. Before, you were storing the ascii codes 0 - 9.
while (guess[0] != array[0] || guess[1] != array[1] || guess[2] != array[2]){
You need to compare each value of the array individually.
You need to store the number before sampling the characters.

How to catch all the values which is returned by this program?

public class Test {
static int nthDigit(int number, int n)
{
int digit = 0;
for (int i = 0; i <= n; i++) { // Assumes n is >= 0
digit = number % 10;
number /= 10;
}
return digit;
}
public static void main(String args[]) {
System.out.println(nthDigit(2314, 4));
}
}
Now output of this program is 0
When I perform unit testing it first returns 4 then 1,3,2 respectively.....
I don't know where I have done the mistake is there any other way to get the output 4,1,3,2
respectively....
You can also do:
return new Integer(String.valueOf(number).substring(n-1,n));
The error in your code is in the return statement/ or your use of it.
digit = number % 10;
If what you want is for the string 4 3 2 1 to be written to the output stream, then you probably want to do this
static String nthDigit(int number, int n)
{
String digit = 0;
for (int i = 0; i <= n; i++) { // Assumes n is >= 0
digit += (number % 10).ToString();
number /= 10;
}
return digit;
}
Notice I changed the return type of the method, and I changed the operator used to populate digit from '=' to '+=' to ensure all values are captured.
If it is the case that you instead want the sum of the values returned, then you would change your code like so
static int nthDigit(int number, int n)
{
int digit = 0;
for (int i = 0; i <= n; i++) { // Assumes n is >= 0
**digit += number % 10;**
number /= 10;
}
return digit;
}
I revert the int return type back to what you originally had, but I keep the operator change I had made earlier.
static int nthDigit(int number, int n)
{
n = String.valueOf(number).length() - n;
int digit = 0;
for (int i = 0; i <= n; i++) {
digit = number % 10;
number /= 10;
}
return digit;
}
public static void main(String args[]) {
System.out.println(nthDigit(2314, 1)); // 2
System.out.println(nthDigit(2314, 2)); // 3
System.out.println(nthDigit(2314, 3)); // 1
System.out.println(nthDigit(2314, 4)); // 4
}
What I did was instead of starting with n as the nth digit, I had it start at the opposite side of the number to it. So instead of the 4th digit, I would have used the 1st digit. To do that, I subtracted n from the length of the number (that's the complement of it, if you've ever taken a probability course).

Categories