I'm having trouble with some code. This code's purpose is just to take user-inputted numbers, append them to a string, and create a histogram representing the amount of numbers in each 5 number range from 1 to 50. Ex.
1 - 5: ***
6 - 10: ********
11 - 15: *
etc.
Here is the code:
public class Ch10Ex4 {
public static int number;
public static ArrayList<Integer> numbers = new ArrayList<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
getNums(1, 50);
}
histogram(1, 50, 5);
System.out.println();
}
public static void getNums(int low_num, int high_num) {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number between " + low_num +
" and " + high_num + ": ");
number = sc.nextInt();
} while (number < 1 || number > 50);
System.out.println(number + " has been added sucsessfully.");
numbers.add(number);
}
public static void histogram(int low, int high, int range) {
int temp_low = low;
int temp_high = low + (range - 1);
for (int i = 0; i < high / range; i++) {
System.out.print("\n" + temp_low + " - " + temp_high + ": ");
for (int arr:numbers) {
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
}
temp_low += range;
temp_high += range;
}
}
}
I had a previous version of this code where I would call histogram() with two parameters. These would be the lowest number and the highest number like usual but no int range parameter. And I didn't have the outermost for-loop. I would have to call histogram 10 times ex.
histogram(1, 5);
histogram(6, 10);
histogram(11, 15);
etc.
Basically, I would call it for every set of five numbers. It worked but it was super inefficient and not very reusable. The problem is that when I run this code (entering numbers 1- 10), I get this:
1 - 5: **********
6 - 10: *****
11 - 15:
16 - 20:
etc.
The first set of five outputs an asterix for every number in the array.
Sorry for the incredibly long post. Any help is much appreciated and thank you in advance.
The bug is that you are using i in this if-statement.
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
Switch it to arr and you should be good.
Related
I am working on a project that take in a starting number and a number of primes then outputs a table with each prime number after your starting number until it reaches your number of primes. I wrote a program to find the prime numbers but im having trouble getting the output to format in a table. I know i need to use nested for loops to build the table but im not sure how to go about starting that. Here is my code so far:
class Tester2{
public static void main(String[] args){
int number = 750000; //starting number
int nofn = 12; //number of primes to find
int primecount = 0;
while(primecount < nofn){
if(isPrime(number)){
primecount ++;
System.out.println(primecount + " " +number);
}
number++;
}
}
//determins if num is prime
private static boolean isPrime(int num){
int divisor = 2;
boolean itIsPrime;
while(num % divisor != 0){
divisor++;
}
if(divisor == num)
itIsPrime = true;
else
itIsPrime = false;
return itIsPrime;
}
}
Currently my code returns
1 750019
2 750037
3 750059
4 750077
5 750083
6 750097
7 750119
8 750121
9 750131
10 750133
11 750137
12 750151
and I am looking for it to return
Row #: 1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
Row #: 2--> 750137 750151
Here you go. I also improved your isPrime method to loop until sqrt(num) instead of num, so it should be much faster now:
public class Test {
public static void main(String[] args) {
int number = 750000; // starting number
int nofn = 100; // number of primes to find
int primecount = 0;
int row = 0, col = 0;
while (primecount < nofn) {
if (isPrime(number)) {
primecount++;
if (col++ == 0)
System.out.print(String.format("%3d-->", ++row));
System.out.print(String.format(" %6d", number));
if (col == 10) {
System.out.println();
col = 0;
}
}
number++;
}
}
private static boolean isPrime(int num) {
final int last = (int) Math.sqrt(num);
for (int divisor = 2; divisor <= last; ++divisor) {
if (num % divisor == 0)
return false;
}
return true;
}
}
Output:
1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
2--> 750137 750151 750157 750161 750163 750173 750179 750203 750209 750223
3--> 750229 750287 750311 750313 750353 750383 750401 750413 750419 750437
4--> 750457 750473 750487 750509 750517 750521 750553 750571 750599 750613
5--> 750641 750653 750661 750667 750679 750691 750707 750713 750719 750721
6--> 750749 750769 750787 750791 750797 750803 750809 750817 750829 750853
7--> 750857 750863 750917 750929 750943 750961 750977 750983 751001 751007
8--> 751021 751027 751057 751061 751087 751103 751123 751133 751139 751141
9--> 751147 751151 751181 751183 751189 751193 751199 751207 751217 751237
10--> 751259 751273 751277 751291 751297 751301 751307 751319 751321 751327
You are using System.out.println every time you need to print. This prints a new line every time a prime is found. What you need to do is use the function System.out.print to print your information. Then, after a 10 primes have been found, implement the function System.out.println.
if(isPrime(number)){
primecount ++;
if(primecount%10==0)
System.out.println(number+" ");
else
System.out.print(number+" ");
}
Not clear what you mean by table. If you just want to print 10 prime numbers on 1 row you can do:
while(primecount < nofn){
if(isPrime(number)){
primecount ++;
System.out.print(primecount + " " +number);
if (primecount%10==0)
System.out.println();
}
number++;
}
To print the row number this should be the code.
public static void main(String[] args) {
int number = 750000; //starting number
int nofn = 12; //number of primes to find
int primecount = 0;
int rowCount = 1;
System.out.print(rowCount + "--> ");
while (primecount < nofn) {
if (isPrime(number)) {
primecount++;
System.out.print(number + " ");
if (primecount % 10 == 0) {
System.out.println();
rowCount++;
System.out.print(rowCount + "--> ");
}
}
number++;
}
}
I mean if you just want to skip it after like 8 entries, you have to do a nested loop how you said.
Not a very good solution, since it could get stuck in the while loop and its not beautiful code at all, but I guess it could work somehow like this:
Edited
int rowCount = 0;
while(primecount < nofn){
if(isPrime(number)){
if(primeCount% 10 == 0) {
rowCount++;
System.out.println("Row #: " + rowCount + "-->");
}
primecount ++;
System.out.print(" " +number); // print not printl
}
number++;
}
I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number < 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
// convert to binary by successively dividing by larger factors of 2
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
if (number / factorOfTwo >= 1) {
System.out.print("1");
number -= factorOfTwo;
} else
System.out.print("0");
}
} // end of main
}// end of class
You have a problem that you are writing the number backwards. You need to start with the highest bit first
for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {
When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1
You could take the easy way out and use:
Integer.toBinaryString(int i) then print the string to the console.
Check it out here.
public class DCTB {
public void convertor(int n)
{
for(int i=0;i<10;i++)
{
int arr=(int) (n%2);
n=n/2;
System.out.println(Integer.toString(arr));
}
}
public static void main(String args[])
{
DCTB obj=new DCTB();
obj.convertor(10);
}
}
I have the following program to write:
An interesting (yet unsolved) question in mathematics is called "hailstone numbers". This series is produced by taking an initial integer and if the number is even, dividing it by 2. If the number is odd, multiply it by 3 and add 1. This process is the repeated.
For example: An initial number of 10 produces: 10, 5, 16, 8, 4, 2, 1, 4, 2, 1... An initial value of 23 produces: 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1...
Note that both numbers eventually reach the 4, 2, 1, 4, 2, 1... cycle.
Create an application that offers the user three different ways to run this program.
Option 1: Print the hailstone numbers for a single entry and its length
Example: Input> 10 10, 5, 16, 8, 4, 2, 1 Length 7
Option 2: Print all of the hailstone numbers from 4 to a given entry
Example: Input> 6 4, 2, 1 Length 3 5, 16, 8, 4, 2, 1 Length 6 6, 3, 10, 5, 16, 8, 4, 2, 1 Length 9
Option 3: Print out the number with the maximum number of iterations need to reach the cycle and which starting number produces this maximum from 4 to the number entered.
Example: Input> 6 Longest: 6 Length: 9
In writing this program you must implement the following method...
/**
*
* #param num Number that a hailstone chain will be generated
* #param showNumbers true if list of numbers is shown to screen
* #return Count of the numbers in the num hailstone chain.
*/
private static int hailStone(int num, boolean showNumbers) {
// your code
}
This is the code I've written so far:
public static void main(String[] args) {
int a = getInt("Give a number: ");
System.out.print("How would you like to run the program? Option 1 prints hailstone numbers for a single entry and its length." +
"Option 2 prints all the hailstone numbers from 4 to a given entry. Option 3 prints the number with the maximum number" +
"of iterations needed to reach the 4, 2, 1 cycle.");
int option = console.nextInt();
boolean showNumbers = (option == 1 || option == 2);
hailStone(a, showNumbers);
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
private static void hailStone (int a, boolean showNumbers) {
if (showNumbers == true) {
if (a % 2 == 0) {
for (int i = 0; i < 50; i++) {
for (int j = 0; j <= i; j++)
a /= 2;
System.out.print(a + " ");
a *= 3;
a += 1;
System.out.print(a + " ");
}
} else {
for (int i = 0; i != a; i++) {
}
}
} else {
}
}
I feel like I've hit a brick wall because I have no idea how to implement all these options in the method my teacher is requiring us to use. Plus, I can't seem to get even the basic hailstone chain to print. Help?
The HailStone algorithm should not be hard to implement. It will actually be much easier if you make it a recursive function, since that is more natural Writing it as an iterative function is probably what is causing your issues.
This should be enough to get you started, this is a working HailStone implementation using a recursive function. You can implement the rest of the project requirements quite easily once you've got the algorithm working... but I'd like to challenge you to convert this into a working iterative function once you get the features correct and to write unit tests to test the program. (TDD dictates that you should write your tests BEFORE you write the actual implementation. This is a great practice that is often skipped due to time constraints and the perception that a strong test suite is overkill.)
HailStone.java
public class HailStone {
/* static variable to count calls to hailStone */
public static int iterCount = 0;
/* This variable is a senti */
public static boolean isRepeating = 0;
/* Simple main function */
public static void main(String[] args) {
// TODO:
// Either parse args or use a scanner to get input.
// Args = verbose, entryPoint
hailStone(10, true);
}
/* Recursive hailStone implementation */
private static void hailStone(int a, boolean showNumbers) {
// start off by printing the numbers if showNumbers is true
if (showNumbers) {
System.out.printf("Iteration #%d: %d\n", ++iterCount, a);
}
// base case: a = 1 => most important part of recursion
if (a == 1) {
if (isRepeating) {
return;
}
isRepeating = true;
}
// check if a is odd
// You can use modulo divison, but we'll use bitwise &
/* Explained: [ bitwise AND... bits that are set in a AND in 1 ]
**********************************************
Case 1: a is even =>
a = 10
10 in binary is 00001010
1 in binary is 00000001
------------------------------
10 & 1 in binary is 00000000
Case 2: a is odd =>
a = 10
11 in binary is 00001011
1 in binary is 00000001
------------------------------
11 & 1 in binary is 00000001
**********************************************
set(X) = set of all even numbers
set(Y) = set of all odd numbers
{
x is any arbitrary number in set X,
y is any arbitrary number in set Y
}
x & 1 will ALWAYS equal 0 -\
>- know this. bitwise hacks rock.
y & 1 will ALWAYS equal 1 -/
*/
if ((a & 1) == 1) {
a *= 3;
a += 1;
} else {
a /= 2;
}
// Tail recursion.
hailStone(a, showNumbers);
return;
}
}
without all the comments and extra stuff:
public class HailStone {
public static int iter_count = 0;
public static void main(String[] args) {
hailStone(10, true);
}
/* Recursive hailStone implementation */
private static void hailStone(int a, boolean showNumbers) {
if (showNumbers) {
System.out.printf("Iteration #%d: %d\n", ++iter_count, a);
}
// base case: a = 1
if (a == 1) {
return;
}
if ((a & 1) == 1) { // a is odd:
a *= 3;
a += 1;
} else {
a /= 2;
}
hailStone(a, showNumbers);
return;
}
}
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("How would you like to run the program?");
System.out.println(" [1] - print hailstone numbers for a single entry and its length.");
System.out.println(" [2] - print all hailstone numbers from 4 to a given entry.");
System.out.println(" [3] - print the number with the maximum number of iterations needed to reach the 4, 2, 1 cycle.");
int option = queryInt("Option: ", 1, 3);
switch (option) {
case 1: {
int seed = queryInt("INPUT> ", 1, Integer.MAX_VALUE);
hailStone(seed, true);
break;
}
case 2: {
int maxSeed = queryInt("INPUT> ", 4, Integer.MAX_VALUE);
for (int i = 4; i <= maxSeed; i++) {
hailStone(i, true);
}
break;
}
case 3: {
int maxSeed = queryInt("INPUT> ", 4, Integer.MAX_VALUE);
int longestChain = 0;
int longestChainLength = 0;
for (int i = 4; i <= maxSeed; i++) {
int length = hailStone(i, false);
if(length > longestChainLength) {
longestChain = i;
longestChainLength = length;
}
}
System.out.println("Longest: " + longestChain + " Length: " + longestChainLength);
break;
}
}
}
private static int queryInt(String prompt, int min, int max) {
while (true) {
System.out.print(prompt);
String input = console.nextLine();
try {
int result = Integer.parseInt(input);
if (result >= min && result <= max) {
return result;
} else {
System.err.print("Expected a number ");
if (min == Integer.MIN_VALUE) {
System.err.println(" less than or equal to " + max);
} else if (max == Integer.MAX_VALUE) {
System.err.println(" greater than or equal to " + min);
} else {
System.err.println(" between " + min + " and " + max);
}
}
} catch (NumberFormatException ex) {
System.err.println("Not a number: " + input);
}
}
}
private static int hailStone(int num, boolean showNumbers) {
int result = 1;
for (Iterator<Integer> chain = iterateHailStone(num); num != 1; num = chain.next(), result++) {
if (showNumbers) {
System.out.print(num + ", ");
}
}
if (showNumbers) {
System.out.print(num);
System.out.println(" (length=" + result + ")");
}
return result;
}
private static Iterator<Integer> iterateHailStone(int seed) {
return new Iterator<Integer>() {
int value = seed;
#Override
public boolean hasNext() {
return true;
}
#Override
public Integer next() {
if (value % 2 == 0) {
value /= 2;
} else {
value *= 3;
value++;
}
return value;
}
};
}
How do I make my program to stop at the user's input?
Here is my code:
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
if (i < x)
System.out.print(printFib(i) + " ");
else if (i > x)
break;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
So, if I enter 10 my program should stop before the number. Example:
Input: 10
Output: 0 1 1 2 3 5 8
But instead I get 0 1 1 2 3 5 8 13 21 34
How can I fix it?
int x = input.nextInt();
int fib = 0;
while (fib < x){
System.out.print(printFib(fib)+ " ");
fib++;
}
}
Don't use a for loop which right now you're using to print out Fibonacci numbers until the number of items printed is less than the entered number. Instead use a while loop that stops when the Fibonacci number itself is greater than the entered number.
Since this is likely homework, I'm just going to give this suggestion and not a code solution, but please give a solution a try, and if still stuck, come back with questions.
Pseudocode
Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
display current fibonacci number
calculate next fibonacci number and place in variable
end while loop
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
int i = 0;
while ( printFib(i) <= x ) {
System.out.print(printFib(i) + " ");
i ++ ;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
While the number return from the printFib() method is less than and equal to the user input, it then runs the method. I've tried the code and it works.
The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}