numbers getting append at end while printing - java

I am working with a program which mimics digital clock. While running it on terminal, my results are like 21:2:139 the 9 append at the end. However, on java console it print as perfect 20:59:0.
my code:
public static void myClock(int h, int m) throws Exception{
//int minutes = m;
int s = 00;
while (true) {
if(s != 60) {
System.out.print("\t\t"+h+":"+m+":"+s+"\r");
Thread.sleep(50);
s += 01;
}else {
m += 1;
s=00;
if(m==60) {
m = 00;
h += 1;
}
}
}
}
I don't know why it's happening because I am new to linux and java.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Unable to print Large # of Primes to Console

I've been having an issue with the following program:
public class PrimeFinder implements Runnable {
Thread go;
StringBuffer primes = new StringBuffer();
int time = 0;
public PrimeFinder() {
start();
while (primes != null) {
System.out.println(time);
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
// do nothing
}
time++;
}
}
public void start() {
if (go == null) {
go = new Thread(this);
go.start();
}
}
public void run() {
int quantity = 1_000_000;
int numPrimes = 0;
// candidate: the number than might be prime
int candidate = 2;
primes.append("\nFirst ").append(quantity).append(" primes:\n\n");
while (numPrimes < quantity) {
if (isPrime(candidate)) {
primes.append(candidate).append(" ");
numPrimes++;
}
candidate++;
}
System.out.println(primes);
primes = null;
System.out.println("\nTime elapsed: " + time + " seconds");
}
public static boolean isPrime(int checkNumber) {
double root = Math.sqrt(checkNumber);
for (int i = 2; i <= root; i++) {
if (checkNumber % i == 0) {
return false;
}
}
return true;
}
public static void main (String[] arguments) {
new PrimeFinder();
}
}
The program will count the time it takes to Print all Primes to the console.
beginning at 0 seconds to x (when the program completes)
Then will print x number of prime numbers (line 29: quantity = 1_000_000).
Then will print "Time Elapsed: x seconds
when I run the program with a smaller quantity (ex:10) it will print up to '29' (the 10th prime).
I'm assuming there is some limitation in eclipse that is preventing a large quantity of numbers from being printed to the console.
Edit: at exactly 5572 the output to the console will be cleared
this is the output:
how many primes would you like to see?
5572
0 //this is time the program has ran
First 5572 primes:
Time elapsed: 0 seconds.
when copy and pasting here the numbers carried over, so its just disappeared from the console.
Your console output is probably limited. In Eclipse, got to...
Window > Preferences > Run/Debug > Console
Uncheck the Limit console output check box.
console output was being printed on one line, added "\n" for the if statement on lines: (41-46)
if (isPrime(candidate)) {
primes.append(candidate+ "\n").append(" "); //if candidate is prime, print # then space " "
numPrimes++;
}
candidate++;
}
Now prints vertically.

given int X,find Y such that (X+Y) is pallindrome in binary format.works fine with values upto 12345 not working with values 123456 and above

public class aevi{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
long num=s.nextLong();
long i=0,j;
while(i<num)
{
long p=1,sum=0,reversesum=0;
j=num+i;
while(j>0)
{
System.out.print(j%2+" ");
sum+=(j%2)*p;
p=p*10;
j=j/2;
}
long r=sum;
System.out.print(r+" ");
while(sum!=0)
{
reversesum=(reversesum*10)+(sum%10);
sum=sum/10;
}
System.out.println(reversesum);
if(reversesum==r)
{System.out.println(i);
break;}
i++;
}
}
}
whats wrong with this code.The program is about " given a number X.find minimium positive integer Y required to make binary representation of
(X+Y) palindrome.for eg:X=6 Y=1".It works fine with values upto 12345 but it is not working with values 123456 and above.
To tell the truth, it is hard to read your code and find problem. I think it is too complicated with such simple problem. I offer you another solution.
E.g. you entered x=6, this is 110 in binary format. Your goal is to find another minimal value y that x+y=<binary palindrome>. For 110, maximum palindrome id 111 which is 7. So, all you need is just find a minimal 0 <= y <= (7-6) where x+y=<binary palindrome>.
Here is the code example. It is pretty easy and simple.
public static long toBinaryPalindrome(long num) {
for (long i = 0, total = allBits(Long.toBinaryString(num).length()) - num; i <= total; i++)
if (isBinaryPalindrome(num + i))
return i;
return -1;
}
private static boolean isBinaryPalindrome(long num) {
String str = Long.toBinaryString(num);
return str.equals(new StringBuilder(str).reverse().toString());
}
private static long allBits(int len) {
long res = 0;
for (int i = 0; i < len; i++)
res |= 1 << i;
return res;
}

Android - Simplifying Radicals

I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}

which jar file can be used to play an audio file in android

When I was searching through google I found a java program created in netbeans to calculate the bpm of a song. It was working with a lot of JAR files.
I used the same code for my android app and it showed lot of errors due to the missing of only one JAR file. I added the JLayer1.0.1 jar file and all the errors were cleared.
Now the app is working good but the bpm calculation is creating some new problems. It gives the bpm of a song which is less than 1 min but the others songs are not always been in process for a hour. And the songs are not been played in the background.
When I checked with the Java program there it is calculating the bpm of all songs and the songs are been played and I can hear it.
What is the problem I am facing here? Is this all because of the JAR file, am I supposed to use any other JAR files? Please help me friends....
I am adding a part of my code
Player player = new Player(new FileInputStream("//sdcard//taxi.mp3"), output);
public class BPM2SampleProcessor implements SampleProcessor {
private Queue<Long> energyBuffer = new LinkedList<Long>();
private int bufferLength = 43;
private long sampleSize = 1024;
private long frequency = 44100;
private long samples = 0;
private long beats = 0;
private static int beatThreshold = 3;
private int beatTriggers = 0;
private List<Integer> bpmList = new LinkedList<Integer>();
public void process(long[] sample) {
energyBuffer.offer(sample[0]);
samples++;
if(energyBuffer.size() > bufferLength) {
energyBuffer.poll();
double averageEnergy = 0;
for(long l : energyBuffer)
averageEnergy += l;
averageEnergy /= bufferLength;
double C = 1.3; //a * variance + b;
boolean beat = sample[0] > C * averageEnergy;
if(beat)
{
if(++beatTriggers == beatThreshold)
beats ++;
}
else
{
beatTriggers = 0;
}
if(samples > frequency * 5 / sampleSize) {
bpmList.add(getInstantBPM());
beats = 0;
samples = 0;
}
}
}
public void init(int freq, int channels) {
frequency = freq;
}
public int getInstantBPM() {
return (int)((beats * frequency * 60) / (samples * sampleSize));
}
public int getBPM() {
Collections.sort(bpmList);
return bpmList.get(bpmList.size() / 2);
}
public long getSampleSize() {
return sampleSize;
}
public void setSampleSize(long sampleSize) {
this.sampleSize = sampleSize;
}
}
public class EnergyOutputAudioDevice extends BaseOutputAudioDevice {
private int averageLength = 1024; // number of samples over which the average is calculated
private Queue<Short> instantBuffer = new LinkedList<Short>();
public EnergyOutputAudioDevice(SampleProcessor processor) {
super(processor);
}
#Override
protected void outputImpl(short[] samples, int offs, int len) throws JavaLayerException {
for(int i=0; i<len; i++)
instantBuffer.offer(samples[i]);
while(instantBuffer.size()>averageLength*channels)
{
long energy = 0;
for(int i=0; i<averageLength*channels; i++)
energy += Math.pow(instantBuffer.poll(), 2);
if(processor != null)
processor.process(new long[] { energy });
}
}
public int getAverageLength() {
return averageLength;
}
public void setAverageLength(int averageLength) {
this.averageLength = averageLength;
}
}

Categories