Dr.Java related to ASCII Displayer - java

I want to generate a sequence of numbers where: I want to compute the next number in the sequence by: (if the number is even, divide it by 2) and (if the number is odd multiply it by 3 and add 1).
I am using ASCIIPrompter and I input the starting number which is 29.
The final display should repeatedly display the number in the sequence and generate the next number based on the conjecture above. The problem with my code is "num = even" gives me an error and i dont know how to fix this error. HELP IS GREATLY APPRECIATED THANKS.
import java.awt.*; // for Color class
import static BasicIO.Formats.*; // for getCurrencyInstance, etc.
import static java.lang.Math.*; // for math constants and functions & random
import static java.awt.Color.*; // for Color constants (e.g. RED)
public class sequence {
private ASCIIDisplayer display;
private ASCIIPrompter prompt;
public sequence() {
display = new ASCIIDisplayer();
prompt = new ASCIIPrompter();
int num;
prompt.setLabel("starting Number");
num = prompt.readInt();
for (int i = 1; i <= 5; i++) {
if (num = even) {
num = num / 2;
} else {
if (num = odd) {
num = num * 3 + 1;
}
}
display.writeDouble(num);
}
display.close();
prompt.close();
}; // constructor
public static void main(String[] args) {
sequence c = new sequence();
};
}

= is an asssignment
if (num = even) {
Thats infact assigning the (undefined?) value even to variable num. Try this instead:
if (num % 2 == 0) {
And instead checking for odd in separate if you could simply use } else { - there is no third case for integers.

Related

Reversing an integer in binary representation

I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}

Multiplying digits of a number until you reach a one digit number

Assume, you input the number 546, then you should find the product of its digits, which is 546=120, then multiply the digits of 120 until and so on, continue until you get a one digit number.
Here's the code I wrote, but the loop doesn't work correctly and I've tried to fix it, but nothing changed. Could you please help me?
import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while(n>10) {
int current = n;
while (current != 0) {
product = product * (current % 10);
current = current / 10;
n = product;
System.out.println(product);
}
}
}
}
For a different take on the solution you can use a recursive lambda
import java.util.Scanner;
import java.util.function.IntFunction;
public class Product {
// this simply reduces the number to the product of its digits.
static IntFunction<Integer> prod =
(a) -> a < 10 ? a : a % 10 * Product.prod.apply(a / 10);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please input the number");
int n = keyboard.nextInt();
// Now continue applying the lambda until the result is < 10.
while (n > 10) {
n = prod.apply(n);
}
System.out.println(n);
}
}
I think you are looking something like the code below:
import java.util.Scanner;
public class Main {
public static int numberOfProducts(String number) {
int product = 1;
do {
for (int i = 0; i < number.length(); ++i){
// This line converts the every digit of the number string to an integer.
product *= number.charAt(i) - '0';
}
// Remove this line, if you don't want to print the product of each iteration.
System.out.println(number);
// Update number with the new product.
// This line converts the int product to a new string.
number = "" + product;
} while (product > 10);
return product;
}
public static void main(String[] args) {
System.out.print("Please input the number: ");
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
// Treat number as a string for easier indexing.
String number = "" + a;
System.out.println(numberOfProducts(number));
}
}
When the above code runs, with 546 as input, it outputs:
Please input the number: 546
546
120
0
After looking through your code, your issue seems to be in this expression:
current % 10.
The modulo operation gives you the remainder of a division by ten.
In the case of your input 120, the result of that operation would be 0.
Following the rest of your application logic, your iteration variable will be set to zero, ending your loop immediately.
I will not give you copy-paste code to fix this problem, as it seems like a programming course assignment. I will however help you solve it.
My suggested fix is to change your approach to this problem and not try to solve this the mathematical way, but rather in a way that takes advantage of the Java programing language.
You could change your input from an Integer to a String.
In which case, you can use String.length() to ensure your requirement is fulfilled when exiting the loop.
In your loop, you split the String into substrings of length 1. Afterwards, you just multiply these.
When the loop exits (because String length is no longer greater than 1) you will have your intended result.
Good luck!
Actually your code is very close to being correct, the only thing you're doing wrong is that you are not resetting the product variable between iterations. You simply need to move the int product = 1; instruction inside the outer while loop.
Also, if you want a single digit at the end, your condition should be while(n >= 10) or while(n > 9), since 10 is still 2 digits, so we need one more iteration !
Final remark: sometimes it's easier to break your code into smaller pieces. It is easier to understand and easier to test/debug ! For example you could have first created a function productOfDigits(n) that returns the result of a single iteration, and then another function productOfDigitsUntilSingleDigit(n) that repeatedly calls the previous function.
import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
if(product > 10) {
System.out.println("Intermediate result="+product);
numberOfProducts(product);
}
else
System.out.println("Final 1 digit product="+product);
}
}
function getProductUntilSingleDigit(n) {
let product = 1;
while (n > 0 || product > 9) {
if (n == 0) {
n = product;
product = 1;
}
product = product * (n % 10);
n = Math.floor(n / 10);
}
return product;
}
console.log(getProductUntilSingleDigit(546));

checking if a number is divisible by 2 in an if statement

I am working with a piece of code that checks if a number is divisible by 2, 12 and 15.
I am working with Java for the first time, and I do not understand how to use it, and so I have come here!
import java.lang.*;
import java.math.*;
public class PrExMa {
public static void main(String[] args) {
//variables
BigInteger num;
BigInteger two, tw, fi;
num = new BigInteger("16");
two = new BigInteger("2");
tw = new BigInteger("12");
fi = new BigInteger("15");
//calculations
// problem is here,I am trying to do
if (num.mod(two).equals("0")) {
System.out.print(num);
// with if(num % two == 0) {
//system.out.print(num);
//}
}
}
}
The comparison should be written as:
num.mod(two).equals(BigInteger.ZERO)
Otherwise you'd be comparing a BigInteger with a String, which clearly are different. Also, do you really have to use BigInteger? isn't a plain old long enough? remember, the maximum value for a long is 2^63 - 1, enough for your needs. In that case, the comparison is as simple as this:
num % 2 == 0

Smallest number with digits product of n

I need to find the smallest number which digit numbers product is equal to a given num.
import java.util.Scanner;
class timus_1014_2 {
public static void main(String[] args){
int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
int j = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 2; i < 10; ++i){
if (n % i == 0) {
arr[j] = i;
j++;
}
}
prod = prod * arr[j];
System.out.print(prod);
}
}
Something is wrong with the logic, whats is the problem when I input 10 it should give 25 but it gives 0. Please give ideas of how to make a program find a number which digits product is a given num.
If I understood your problem correctly you need a number whose product of digits equals a number N. Since you asked for new algorithm , you can chck following code.
Logic:
Note : For number whose prime factors are less than 10
Get all factors from 9 -> 2
add to list
print in reverse or use stack instead of list
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number");
int num = in.nextInt();
List<Integer> lst = new ArrayList<>();
for (int p = 9; p >= 2; p--) {
while (num % p == 0) {
num /= p;
lst.add(p);
}
}
String smallestNumber = "";
for (int i = lst.size() - 1; i >= 0; i--) {
smallestNumber = smallestNumber + lst.get(i);
}
System.out.println("Smallest number : " + smallestNumber);
}
}
Output :
Enter number
10
Smallest number : 25
Enter number
144
Smallest number : 289
Enter number
12
Smallest number : 26
I suggest you look at each error is fix it one by one. I also suggest you use an IDE which will show you the errors and you type and will help ensure you don't have an overwhelming number of errors and you can see if those error disappear based on your corrections.
BTW Often when you use an array for a short piece of code, it can often be eliminate as I suspect it can be removed in your case.
Static methods can not access non-static members of class.
In your case prod is member variable of class but not static. To fix the error , try to make prod as static.
private static int prod = 1;
I would prefer , to make it local variable if no other method is using it.
The problem here is you need to create an object of the particular class to call a particular method associated with it
import java.util.Scanner;
class DigPro {
static int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
DigPro obj = new DigPro();
obj.prime(in.nextInt());
}
public void prime(int n){
for (int i = 1; i < 10; ++i){
for (int j = 0; j < 9; ++j) {
if (n % i == 0) {
arr[j] = i;
}
prod = prod * arr[j];
}
}
System.out.print(prod);
}
}
Here you need to create an object say obj of DigPro class and then call prime(int n) method with that object. Also your division is startint with zero which is changed to one
In above code you are increasing j after the assigning value to arr[j].You should do the following:-
prod = prod * arr[j-1];
Here it will multiply prod with last array updated. That is why you are getting zero. And for your another question find the smallest number which digit numbers product is equal to a given num has similar answer at this link.
Since this is actually a pretty interesting problem, I took the time to come up with a correct solution for all possible integer inputs.
import java.util.*;
public class Main{
public static void main(String[] args) {
System.out.println("Enter number:");
int number = new Scanner(System.in).nextInt();
Stack<String> factors = new Stack<>();
if(number==0){
factors.push("0");
}else if(number==1){
factors.push("1");
}else{
for(int f=9;f>1;f--){
while(number%f==0){
factors.push(Integer.toString(f));
number/=f;
}
}
}
if(number<0){
factors.push("-");
}
if(number>9){
System.out.println("This is impossible.");
}else{
System.out.println("Smallest Number:");
while(!factors.empty()) System.out.print(factors.pop());
}
}
}

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

Categories

Resources