cant get binary to print horizontal and to stop exacution - java

I am making a program that is converting from decimal to binary, octal, and hexadecimal. I am only focusing on the decimal to binary part in this so far. My problems are that the binary when I ask it to convert up to said number print them vertically not horizontally like 010. Also my while statement does not stop exacution if the y input is greater than 1024, which is the highest value I want to be able to be accepted.
import java.util.Scanner;
public class DNS
{
public static void main(String[] args)
{
int y;
Scanner input = new Scanner( System.in);
do
{
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
for(int x=0; x <=y; x++)
{
convertToBinary(x);
}
}
while(y <=1024);
}
public static void convertToBinary(int x)
{
if(x >0)
{
convertToBinary(x/2);
System.out.print(x%2 + " ");
}
System.out.println("");
}
}

remove System.out.println(""); from public static void convertToBinary(int x)
you will be able to print horizontally
and change your do-while to simple while like this
int y;
Scanner input = new Scanner( System.in);
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
while(y <=1024)
{
for(int x=0; x <=y; x++)
{
convertToBinary(x);
}
}
you were checking if y<=1024 after calling convertToBinary() method. you have check if y<=1024 before making a call to convertToBinary() method.

You probably meant to have the empty System.out.println() call (by the way, you can call it with no arguments) after the call to convertToBinary(x) in the main for loop - otherwise empty lines are being printed during each recursion step of each number being evaluated.
for (int x = 0; x <= y; x++) {
convertToBinary(x);
System.out.println();
}
Regarding your other question about stopping if the input is larger than 1024 - this is because the calls to convertToBinary(x) are happening before the check in the while statement. You will need to explicitly break out of the loop to stop this. Personally, I would just use an infinite while loop with explicit checks:
while (true) {
System.out.println("java DisplayNumberSystems");
System.out.println("Enter a decimal value to display to: ");
y = input.nextInt();
if (y < 0) {
System.out.println("That number is not positive!");
break;
}
if (y > 1024) {
System.out.println("That number is too big!");
break;
}
for (int x = 0; x <= y; x++) {
convertToBinary(x);
System.out.println();
}
}

Related

How can I print the amount of times 'while' was executed?

I'm writing a code which will be multiplying 'x' until it'll reach the 'y'.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
do {
x = (int)(x*(1.1f));
}
while(x < y);
}
In the answer I have to get the amount of times 'while' was executed. I'm not sure how to do this.
So general approach would be, create variable i of type int, and increment it at the end of while loop block (this one looks simple actually). So overall, I'd do it this way:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
do {
x = (int)(x*(1.1f));
i++;
} while (x < y);
System.out.println("Loop executed " + i + " times.");
}
If you can use for loop, check out this way of solving your problem:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
for (; x < y; i++)
x = (int)(x*(1.1f));
System.out.println("Loop executed " + i + " times.");
}
}
Thanks to the fact that for loop allows execution of some statement every iteration, you can increment your counter variable everytime loop is looping (this can solve some cases where you use continue; statement).
Basically you need to find out how many times x should be multiplied by 1.1 for it to get larger than y. Or in other words, to what power should 1.1 be raised in order for it to get larger than y/x.
Therefore, an alternative to using a counter would be observing that you need to calculate log1.1(y/x) and round it up to the next int, which in Java can be done with:
Math.ceil (Math.log ((double)y/x) / Math.log (1.1));

what i'm i doing wrong on this algorithm?

I've been stuck on this code for a couple of hours.
The sum is S = 1-x + x^2 - x^3 + x^4.
We ask for X and N with starting value of i = 0.
Whenever the previous exponent (i) is odd we add x^i, and
if the previous exponent is even we subtract x^i.
I've put them on a loop but i can't seem to get the sum correctly.
Can anyone tell me what I'm doing wrong?
Thank you!
import java.util.Scanner;
public class hw1 {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int X = scan.nextInt();
System.out.println("Enter number N");
int N = scan.nextInt();
int sum = 0;
for (int i = 0; i <= N; i++) {
if (i < N) {
if (i % 2 != 0) // if I is even
{
sum = sum - (X ^ i);
} else // if I is odd
{
sum = sum + (X ^ i);
}
}
}
System.out.println("Z is " + sum);
}
}
}
So I fixed a few things in your code:
I switched the ^ operator (which, as #Nick Bell pointed out, is a bitwise exclusive OR) for Math.pow.
I fixed the spelling of your variables x and n. In Java, convention is to give variables names that start with lower-case. Upper-cases (X and N) are reserved for constants (fields marked final) and for classes (as opposed to objects). Note that this is only a convention, and that the code works fine both ways. It just helps in reading the code.
Your odd/even check was inverted: x % 2 == 0 is true for even numbers.
The reason that you inverted your odd/even check was probably the two operations on sum were inverted. Compare with the description of your problem in the first paragraph of your question, you'll see where you went wrong.
The if i < N check was redundant. It you really wanted to limit computation to i < N, you should specify it directly in your first for loop.
I added two try/catch blocks with infinite loops that break when an integer is entered, because your previous code threw an exception and stopped if you entered something else than a well-formed integer (such as letters, or a decimal value). Up to you to keep them or delete them.
By the way, initializing x and n to 0 is now redundant, since your code is guaranteed to assign them another value right away.
This is the updated code.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int x = 0;
while (true) {
try {
x = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
System.out.println("Enter number N");
int n = 0;
while (true) {
try {
n = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
double sum = 0;
for (int i = 0; i <= n; i++) {
if (i % 2 == 0) // if I is even
sum = sum + Math.pow(x, i);
else // if I is odd
sum = sum - Math.pow(x, i);
}
System.out.println("Z is " + sum);
}
}

Tau Numbers Algorithm

I am trying to make a program where a user enters 2 numbers, and then the program gives the tau numbers in this gap.
"Tau" number is the number which can divided by its total number of dividers.For example (1,2,3,4,6,8,12,24) all this numbers can divide 24. There is 8 numbers then 24 can divided by 8. So we can say 24 is a tau number.*
There is a mistake at second for loop I think but I cannot understand where is it.
import java.util.Scanner;
public class tauNumber {
public static void main(String [] args){
int start=0,stop=0,count=0;
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
start=input.nextInt();
System.out.println("Please enter last number: ");
stop=input.nextInt();
for(int i=0+start;i<=stop;i++){
for(int j=1;j<=start;j++){
if(i%j==0){
count++;
}
}
if(start/count==0){
System.out.println(i+" is a tau number" );
}
}
}
}
Instead of saying "tau number" you should just refer to it as a refactorable number as #Tunaki pointed out.
I would suggest that you split your code up into functions to get a better understanding on whats going on, I think this is what you're looking for:
import java.util.Scanner;
class TauNumber {
public static void main(String[] args){
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
int start=input.nextInt();
System.out.println("Please enter last number: ");
int stop=input.nextInt();
for(int i=start+1; i<stop; i++){
if(refractorable(i)){
System.out.println("Found tau number: "+ i);
break;
}
}
}
public static boolean refractorable(int number){
if(sumDivisors(number) == 0) return false;
if(number % sumDivisors(number) == 0){
return true;
} else {
return false;
}
}
public static int sumDivisors(int number){
int sum = 0;
for(int i=1; i<=number; i++){
if(number % i == 0){
sum++;
}
}
return sum;
}
}
Note: I would also like to point out that when you specify "gap" what do you mean by it? I took it as start < x < stop, because that would be the gap but it could certainly be start < x <= stop.
The fault in your code is that you check whether the quotient of start/count is 0. To check whether start is divisible by count, you should check whether the remainder is 0. Therefore, you should use the modulus (%) operator instead of the division (/) operator.
Below is a function's code that checks whether its argument is a tau number.
private static boolean isTau(int tau){
int count = 0;
for(int i=1; i<=tau; i++){
if(tau % i == 0)
count++;
}
return (tau % count == 0) ; //returns true if 'tau' is a tau number
}
In the main method, you can make use of this function like this:
for(int i=start; i<=stop; i++){
if(isTau(i))
System.out.println(i+" is a tau number");
}

How do you get a Scanner to store and repeat in a while loop

I need to write a program which accepts non-negative double type of
numbers as
income amounts one by one unti
l a negative number
is entered
, and the negative number ends the
program. When the program is completed by entering a negative number
, it prints out the
minimum, average, and maximum for the set of entered incomes (excluding the last negative
number
be
cause it only indicates the end of user input).
package incomeapp;
import java.util.Scanner;
/**
*
* #author Kenneth
*/
public class IncomeApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
int count = 0;
double i = sc.nextDouble();
while (i > 0){
double nextDouble;
nextDouble = sc.nextDouble();
if (i < 0){
break;
}
}
}
}
There's a few issues with your code here:
You never actually increment either sum or count
You read input into i before the loop, but then you read into nextDouble inside the loop and the loop condition only checks i - which never changes.
You never print out the minimum, average, and maximum
The condition in the while and if statements are redundant (apart from the if condition accepting 0 which the while condition doesn't)
Now, this seems very much like a programming assignment to me so I'm not going to post the complete code for you. Here's what you should do to fix your code though:
Increment sum and count in the loop.
Use either i or nextDouble - not both.
Print the desired output after the loop
Pick one way of terminating the loop. Here's two ideas on how to do it:
double i = sc.nextDouble();
while (i > 0) {
// Do something with i
i = sc.nextDouble();
}
or
while (true) {
double i = sc.nextDouble();
if (i <= 0) {
break;
}
// Do something with i
}
Try this:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
double max = 0;
double min = Double.MAX_VALUE;
int count = 0;
double nextDouble;
while (sc.hasNext()) {
nextDouble = sc.nextDouble();
max = Math.max(max, nextDouble);
if (nextDouble < 0){
break;
}else {
min = Math.min(nextDouble, min);
sum += nextDouble;
count++;
}
}
System.out.println("Average: " + sum/count);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}

My Euclid Algorithm is working very slowly

This code compiles fine, but when I run it, it asks for my two numbers as expected and then just sits there and doesn't do anything at all. I've searched the Internet and worked on this all day. I'm finally caving and asking for help.
Is the issue that it's not looping back up automatically? After 10 hours at this, I've found nothing.
import java.util.Scanner;
public class EA
{
public static void main (String[] args)
{
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
//do the calculations
while(J>0)
{
int Remainder;
Remainder = I % J;
while(Remainder>0)
{
I = J;
J = Remainder;
return;
}
System.out.println("GCD is" + J);
}
}
}
}
Among other things already mentioned, you are confusing while with if. You have put your algorithm logic inside a while loop that only runs if the first input is bad.
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
// You never reach here under ordinary conditions
}
SJuan mention that the return breaks the loop, which is true, but even if it's fixed there are a few other issues:
The inner while never end (infinite loop)
The result will be stored in J - not in I
System.out.println("GCD is " + I); Should be printed outside of the outer while!
The "heart" of your program should do this:
// we get here with valid values stored in I,J
int Remainder = I % J;
//do the calculations
while(Remainder>0)
{
I = J;
J = Remainder;
Remainder = I % J;
}
System.out.println("GCD is " + J);
There are more than 1 error: the return in the while, the algorithm and the brackets of the first while.
1) When you resolve the issue of zero, the brackets of the while must be closed suddenly after you re-assign the value of the variable J.
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
2) The algorithm for computing the gcd is the following:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod t
a := t
return a
Here is the correct version of your code:
public static void main(final String[] args) {
// get first integer from user
final Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
// resolve the issue of zero
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
// do the calculations
while (J != 0) {
int Remainder;
Remainder = I % J;
I = J;
J = Remainder;
}
System.out.println("GCD is" + I);
}
The return in the middle of the loop will end the execution.
This one
while(Remainder>0)
{
I = J;
J = Remainder;
return; <------- THIS IS THE RETURN THAT BREAKS ALL
}
so it does not get to the System.out.println.
UPDATE: Also, you do input.nextInt() twice for J. Probably from your description, it keeps waiting for you for entering the third integer.
Well Euclid's algorithm has a drawback as both the inputs should be non zero to compute the Greatest common divisor . But if you want to find out the GCD when one of the input is a zero ('0') tweak the logic a bit . When one of the input is zero the GCD is 1, and 'a' should be greater than 'b' to compute GCD. Check the snippet below:
if (a < b) {
int temp = a;
a = b;
b = temp;
}
if (b == 0) {
System.out.println("1");
} else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}

Categories

Resources