Variable Declaration Problems - java

I can't figure out why eclipse wants me to delete the ";" and replace it with with a ",".
numberOfTimes1 = numberOfTimes + numberOfDelayTimes;
I'm guessing it's some simple syntax thing that I forgot about. Could you please explain why it's doing that and also how to fix it.
Entire Program
public class Spam {
public static void main(String[] args) {
//1- Taking an instance of Timer class.
Timer timer = new Timer("Printer");
//2- Taking an instance of class contains your repeated method.
timeso t = new timeso();
timer.schedule(t, 0, 10);
}
}
class timeso extends TimerTask {
//times member represent calling times.
private int times = 0;
int time = 6; //How long do you wish for the spamming to run?
int numberOfTimes = time * 100;
int delayTime = 5; //How long do you wish for the program to wait before spamming?
int numberOfDelayTimes = delayTime * 100;
numberOfTimes = numberOfTimes + numberOfDelayTimes;
String spam;
Random randomGenerator = new Random();
public void run() {
times++;
if (times >= numberOfDelayTimes && times <= numberOfTimes+numberOfDelayTimes) {
try {
Robot typer = new Robot();
//for(int x = 1;x <=randomGenerator.nextInt(5); x++){
// spam = spam + randomGenerator.nextInt(10);
//}
byte[] bytes = "spam".getBytes();
//byte[] bytes = spam.getBytes();
for (byte b : bytes){
int code = b;
// key code only handles [A-Z] (which is ASCII decimal [65-90])
if (code > 96 && code < 123) code = code - 32;
typer.delay(10/bytes.length+1);
typer.keyPress(code);
typer.keyRelease(code);
}
if(times % (randomGenerator.nextInt(25)+1) == 0){
typer.delay(10/bytes.length+1);
typer.keyPress(KeyEvent.VK_ENTER);
typer.keyRelease(KeyEvent.VK_ENTER);
}
}
catch (AWTException e){
}
} else {
if (times >= numberOfTimes){
try{
Robot typer = new Robot();
typer.delay(10);
typer.keyPress(KeyEvent.VK_ENTER);
typer.keyRelease(KeyEvent.VK_ENTER);
} catch(Exception e){
}
//Stop Timer.
this.cancel();
}
}
}
}

You're trying to call a line of code outside of a method or constructor, and this is why the Java compiler (not Eclipse) is complaining. Do that sort of code in the constructor or method, not naked in the class. In fact all that code in your timeso class is incorrect and needs to be in a method or constructor.
Note: you'll want to learn Java naming convention and stick with it, including starting class names with an upper-case letter and method and variable names with a lower-case letter. Doing this will help others (us!) understand your code better.

Related

The array/loop complies correctly, however how do you keep a part of the output the same?

Perhaps i wasn't clear enough. I apologize. I tried condensing and adding images in this edit to make it more clear.
50 Seed Value, 1200 RNG Value.
60 Seed Value, 1200 RNG Value.
In the examples above (for clarity instead of writing it all out), you can see the outputs you get for 50 vs 60. It's not the distinct values I'm concerned. It's the display now. As you can see, the number gets bigger since I put in a new seed value. I want it to display what the 50 seed value is, but have the properties of whatever seed value I put in.
If I put in for example 60, I want to get:
H1 T1 H1 T1 HHH3 TTTTT5 H1 T1 HHHH4 T1 HH2 T1 H1 T1 H1 T1 H1 T1 H1 TTT3 H1 TTT3 H1 TTTT4 H1 T1 HHH3 TT2 H1 T... (just like with the 50 seed value).
BUT it would get 35 distinct values instead of the 30. Let me know if I can be clearer I apologize for being so confusing.
import java.util.Scanner;
import java.util.Random;
public class CoinFlipAnalyzer{
private static final Scanner
stdIn = new Scanner(System.in);
public static void main (String[] args){
// Integer Values:
int totalNumberOfRuns = 0;
int run = 1;
// Boolean Values:
boolean theCoin;
boolean tempVal = false;
// Gathering the Users Input:
System.out.println("Welcome to the coin flip analyzer.\n"
+ "How many flips?");
int numberOfFlips = stdIn.nextInt();
System.out.println("What do you want to seed the random number generator with?");
int rngSeed = stdIn.nextInt();
Random rng = new Random(rngSeed); // Initiates the Random Number Generator.
System.out.println();
// Loop and Array to Decide Whether the Value is Heads or Tail.
long[] runLength = new long[numberOfFlips];
for (int i = 0; i < numberOfFlips; i++) {
theCoin = rng.nextBoolean(); // As requested, I used the nextBoolean expression.
if (theCoin != tempVal) {
if (i > 0) {
System.out.print(run + " ");
}
runLength[run - 1]++;
totalNumberOfRuns++;
run = 1;
}
else {
run++;
}
if (theCoin) {
System.out.print("H");
tempVal = true;
}
else {
System.out.print("T");
tempVal = false;
}
}
System.out.print("...");
System.out.println();
System.out.println("There were a total of " + totalNumberOfRuns +
" distinct runs in the simulation.\nTheir breakdown follows:");
System.out.println();
I think I understand the requirement. In essence, there is some desired width, and if the number of outputs exceeds the width, then print using an ellipses.
There is the StringUtils from Apache Commons that has an 'Abbreviate' method.
public static String abbreviate(String str,
int maxWidth)
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."
To use this (or the other suggestion below), I would remove the immediate output that is being generated in the run, and instead build a String. One could build a char[] as well, but here we will go with a String (or a StringBuilder). There is another advantage to so doing -- it is generally a good practice to separate some of the logic from the output. Plus it would be more testable.
So, if one can use the StringUtils.abbreviate(...), then take the result from the doFlips(...) and pass it to the method, and the result will be done.
/*
* moved the flipping into a method; allow it to build the
* results rather than immediately outputting them
*/
private static StringBuilder doFlips(int numberOfFlips, Random rng)
{
long[] runLength = new long[numberOfFlips];
boolean theCoin;
boolean tempVal = false;
int run = 1;
int totalNumberOfRuns = 0;
// Here we will collect the output; use better name in production
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfFlips; i++) {
theCoin = rng.nextBoolean(); // As requested, I used the nextBoolean
// expression.
if (theCoin != tempVal) {
if (i > 0) {
sb.append(run);
sb.append(" ");
}
runLength[run - 1]++;
totalNumberOfRuns++;
run = 1;
}
else {
run++;
}
if (theCoin) {
sb.append("H");
tempVal = true;
}
else {
sb.append("T");
tempVal = false;
}
}
return sb;
}
If one cannot use the library, it is easy enough to write a chop method:
/**
* Chop the input StringBuilder and give "..." at
* maxOutput.
*
* NOTE: no error checking
*/
private static String ourChop(StringBuilder sb, int maxOutput)
{
if (sb.length() <= maxOutput) {
return sb.toString();
}
// we chop everything past maxOutput - 3
sb.setLength(maxOutput - 3);
sb.append("...");
return sb.toString();
}
So, we can then do the following:
public static void main(String[] args)
{
int seed = 1200;
int maxOutput = 25;
// 50 flips, 25 length max, including ... if needed
StringBuilder res = doFlips(50, new Random(seed));
System.out.println(ourChop(res, maxOutput));
res = doFlips(60, new Random(seed));
System.out.println(ourChop(res, maxOutput));
And we get this output (at 25):
H1 T1 H1 T1 HHH3 TTTTT...
H1 T1 H1 T1 HHH3 TTTTT...
Now, if the goal is to align to the max output of some given run, then one would need to collect all of the runs (50, 60, etc.), and then find the particular value (say the shortest of the outputs; note that in theory in a truly random setting, 60 could have a shorter output than 50, but not when using the same seed). One could then use that determined value to chop to a given output length.
If I have misunderstood the approach, I apologize.

How Locale could be used in multithreaded application to improve performance

In my application I have a method which is called by multiple threads simultaneously. Each thread calls this method many times while running.
private Locale trLoc = new Locale("tr", "TR");
public double calculate(String arg1){
arg1 = arg1.toUpperCase(trLoc);
...
}
This method makes a String.toUpperString(Locale) call which causes a bottleneck because of the HashTable usage within the Locale class. Each thread waits other one while toUpperCase method operates. This situation slows down my application up to three times.
Is there something I'm missing with the usage of the Locale or I must use another class for the same purpose?
Thanks in advance.
After short exploring it looks like JDK can't help you. I suggest get java.lang.ConditionalSpecialCasing class, copy it and fix problem with Hashtable. You may replace Hashtable with HashMap. I do not see any reason for using Hashtable here.
Edit: The solution bellow won't actually work, because the problematic HashTable in the java.lang.ConditionalSpecialCasing class is static and will still be shared by all threads. I suggest that you accept sibnick's answer instead of mine.
One simple solution would be to make trLoc a ThreadLocal: a new instance will be automatically created for each thread (as needed). This will work fine if you have a thread pool or similar: you will only create as many instances of Locale as you have threads in your pool, which should be quite reasonable. And since each thread will access a different instance of Locale, you will no longer have contention to access the synchronized HashTable.
private ThreadLocal<Locale> trLoc = new ThreadLocal<Locale>() {
#Override
protected Locale initialValue() {
return new Locale("tr", "TR");
}
};
public double calculate(String arg1){
arg1 = arg1.toUpperCase(trLoc.get());
...
}
Based on the answer from #sibnick I runned some a JMH benchmark.
upperCaseEN uses Local.ENGLISH
upperCaseTR uses new Locale("tr", "TR")
JDK 8
Benchmark Mode Samples Score Score error Units
s.o.MyBenchmark.upperCaseEN thrpt 25 9680.129 89.485 ops/ms
s.o.MyBenchmark.upperCaseTR thrpt 25 992.973 6.306 ops/ms
JDK 8 patched
Using a patched ConditionalSpecialCasing class using HashMap instead of Hashtable
Benchmark Mode Samples Score Score error Units
s.o.MyBenchmark.upperCaseTR thrpt 25 3331.277 77.691 ops/ms
Another solution could be to first scan the string if it contains a lowercase i. As this seems to be the only character which needs a special handling for toUpperCase in Turkish locale.
if (state.lowercase.contains("i")) {
uppercase = lowercase.toUpperCase(TR_LOCALE));
} else {
uppercase = lowercase.toUpperCase(EN_LOCALE));
}
Which improves the performance already.
Benchmark Mode Samples Score Score error Units
s.o.MyBenchmark.upperCasePatchedTR thrpt 25 8753.116 51.582 ops/ms
edit The code for the benchmarks can be found at
https://github.com/SubOptimal/stackoverflow-answers/tree/master/question-31987777
Building on SubOptimal's suggest of scanning for lowercase 'i', I have have tried a bit code to replace i with an innocuous character, to upper case, and the substituting back. My dodgy performance test does not show a great improvement in speed, YMMV. Do test performance with JMH instead, but you already knew that.
I then had a go at a table based approach. That is fast as expected.
As always, code for information only. Barely tested.
import java.util.*;
import java.util.concurrent.atomic.*;
public class Benchmark {
// Substitute i Turkish toUpperCase.
public static String toUpperCase(String str) {
int index = str.indexOf('i');
if (index == -1) {
return str.toUpperCase(tr);
} else {
char[] array = str.toCharArray();
char[] localised = toUpperCase(array, index);
return String.valueOf(localised);
}
}
private static char[] toUpperCase(char[] array, int index) {
array[index] = 'X';
int next = indexOf('i', array, index+1);
final char[] localised;
if (next == -1) {
String upper = String.valueOf(array).toUpperCase(tr);
int len = upper.length();
if (len == array.length) {
localised = array;
upper.getChars(0, len, localised, 0);
} else {
localised = upper.toCharArray();
}
} else {
localised = toUpperCase(array, next);
}
localised[index] = '\u0130';
return localised;
}
private static int indexOf(char c, char[] array, int off) {
while (off<array.length && array[off] != c) {
++off;
}
return off==array.length ? -1 : off;
}
// Table-based Turkish toUpperCase.
private static final int limit = 1<<9;
private static final char[] table;
static {
Locale locale = new Locale("tr", "TR");
table = new char[limit];
char[] buff = { ' ' };
for (int c=0; c<limit; ++c) {
buff[0] = (char)c;
String upper = String.valueOf(buff).toUpperCase(locale);
if (upper.length() != 1 && c != 223 && c != 329 && c != 496) { // es zett etc
throw new Error("do not run: "+c);
}
table[c] = upper.charAt(0);
}
}
public static String tableToUpperCase(String str) {
int len = str.length();
char[] buff = new char[len];
int i;
for (i=0; i<len; ++i) {
char c = str.charAt(i);
if (c >= limit || c == 223 || c == 329 || c == 496) {
break;
}
buff[i] = table[c];
}
return i==len ? String.valueOf(buff) : str.toUpperCase(tr);
}
// Ropey benchmark.
private static final Locale tr =
new Locale("tr", "TR");
//Locale.ENGLISH;
public static void main(String[] args) {
System.err.println("friingi".toUpperCase(tr));
System.err.println(toUpperCase("friingi"));
int total = 0;
for (int i=0; i<5; ++i) {
long start = System.nanoTime();
total += run();
long time = System.nanoTime()-start;
System.err.println(time/1000_000_000.0);
}
System.err.println(total);
}
private static int run() {
AtomicInteger total = new AtomicInteger(0);
List<Thread> threads = new ArrayList<>();
for (int i=0; i<100; ++i) {
threads.add(new Thread(() -> {
total.addAndGet(runOne());
}));
}
threads.forEach(Thread::start);
threads.forEach(thread -> {
try {
thread.join();
} catch (Exception exc) {
throw new Error(exc);
}
});
return total.get();
}
private static int runOne() {
int sum = 0;
for (int i=0; i<10_000; ++i) {
sum +=
/**/
tableToUpperCase("fringe")
//toUpperCase("fringe")
/*/
"fringe".toUpperCase(tr)
/**/
.length();
}
return sum;
}
}

Recursive print Factorial

So I did search and read abut every factorial listing on this site but I cannot seem to figure out what is wrong with my code. Iv tried multiple different return methods but they all keep failing. Any ideas?
public class RecursivelyPrintFactorial {
public static void printFactorial(int factCounter, int factValue) {
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) // Base case: 0! = 1
System.out.println("1");
}
else if (factCounter == 1) // Base case: print 1 and result
System.out.println(factCounter + " = " + factValue);
}
else { // Recursive case
System.out.print(factCounter + " * ");
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
}
return factValue * printFactorial(factValue - factCounter);
}
}
public static void main (String [] args) {
int userVal = 0;
userVal = 5;
System.out.print(userVal + "! = ");
printFactorial(userVal, userVal);
}
}
I have a feeling I have the equation incorrect in my return but iv tried every combination I can think of. Its driving me insane. Every one reports an error. Any ideas?
return factValue * printFactorial(factValue - factCounter);
I assume that you should be using the "next" values instead of these.
Edit: Also note that the function takes two parameters and is void. Returning factValue times void doesn't make sense.

Java Threading- Am I writing thread-safe code?

I'm currently trying to get into parallel processing, so to do this, I'm writing a program that processes an image, giving information about its color values overall- I am doing some tests on this one class with a randomly generated array of integers, and 4 threads are running to process every 4th pixel, from their respective starting places. I was just wondering if this read is thread-safe? Can multiple threads read the same data structure if that's what I want?
import java.awt.image.BufferedImage;
import java.lang.Thread;
public class ImageProcessor extends Thread {
public static void main(String[] args) {
int[] z = new int[10000000];
for (int i = 0; i < 10000000; i++) {
double a = (Math.random()*1000000);
z[i] = (int) a;
}
ImageProcessor ip = new ImageProcessor();
ip.imgRGBPercent(z);
}
public ImageProcessor() {
}
public void process(int[] x, int startPoint) {
(new Thread(new ReadThread(x, startPoint))).start();
}
public int[] imgRGBPercent(int[] x) {
ReadThread first = new ReadThread(x, 0);
ReadThread second = new ReadThread(x, 1);
ReadThread third = new ReadThread(x, 2);
ReadThread fourth = new ReadThread(x, 3);
Thread a = (new Thread(first));
Thread b = (new Thread(second));
Thread c = (new Thread(third));
Thread d = (new Thread(fourth));
long timeMetric = System.currentTimeMillis();
a.start();
b.start();
c.start();
d.start();
try {
a.join();
}
catch (Exception e) {
}
try {
b.join();
}
catch (Exception e) {
}
try {
c.join();
}
catch (Exception e) {
}
try {
d.join();
}
catch (Exception e) {
}
int redTotal, blueTotal, greenTotal;
redTotal = first.getRGBTotals()[0] + second.getRGBTotals()[0] + third.getRGBTotals()[0] + fourth.getRGBTotals()[0];
blueTotal = first.getRGBTotals()[1] + second.getRGBTotals()[1] + third.getRGBTotals()[1] + fourth.getRGBTotals()[1];
greenTotal = first.getRGBTotals()[2] + second.getRGBTotals()[2] + third.getRGBTotals()[2] + fourth.getRGBTotals()[2];
System.out.println(greenTotal);
System.out.println(System.currentTimeMillis() - timeMetric);
timeMetric = System.currentTimeMillis();
ColorValue cv1 = new ColorValue();
int sum = 0;
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < x.length; i++) {
sum += cv1.getGreen(x[i]);
sum1 += cv1.getRed(x[i]);
sum2 += cv1.getBlue(x[i]);
}
System.out.println(sum);
System.out.println(System.currentTimeMillis() - timeMetric);
int[] out = new int[3];
return out;
}
private class ReadThread implements Runnable {
private int[] colorArr;
private int startPoint, redTotal, blueTotal, greenTotal;
private ColorValue cv;
public ReadThread(int[] x, int startPoint) {
colorArr = x;
this.startPoint = startPoint;
cv = new ColorValue();
}
#Override
public void run() {
//System.out.println("hit");
for (int i = startPoint; i < colorArr.length; i+=4 ) {
redTotal += ColorValue.getRed(colorArr[i]);
blueTotal += ColorValue.getBlue(colorArr[i]);
greenTotal += ColorValue.getGreen(colorArr[i]);
}
}
public int[] getRGBTotals() {
int[] out = new int[3];
out[0] = redTotal;
out[1] = blueTotal;
out[2] = greenTotal;
return out;
}
}
}
Yes. As long as the data structure is not modified while it's being read, you're safe. Every write done before starting a thread will be visible by the started thread.
This logic would concern me a little:
for (int i = startPoint; i < colorArr.length; i+=4 ) {
redTotal += ColorValue.getRed(colorArr[i]);
blueTotal += ColorValue.getBlue(colorArr[i]);
greenTotal += ColorValue.getGreen(colorArr[i]);
}
colorArr is a reference to an array; the reference was passed to the Runnable during the constructor, but the array itself was created outside.
In the complete program you posted, I don't think it's a problem, since this array isn't modified anywhere in your program after the point where you start the threads. But in a larger, "real-world" case, you have to be aware that you're reading colorArr[i] three times and the value may not be the same each time, if there are other threads that could make changes to colorArr. That's one of the things you have to watch out for when writing concurrent code. This would be a little better:
for (int i = startPoint; i < colorArr.length; i+=4 ) {
int color = colorArr[i];
redTotal += ColorValue.getRed(color);
blueTotal += ColorValue.getBlue(color);
greenTotal += ColorValue.getGreen(color);
}
But depending on what your needs are, you may need to take extra steps to make sure no part of the program can modify colorArr at any point while the entire loop is running. Then you need to start looking into lock objects and synchronized, and you'd want to seriously consider setting up a separate class for the colorArr, with methods for modifying and reading the array that are either synchronized methods or contain logic to ensure that things are synchronized properly--by putting the array in its own class, the needed synchronization logic could be encapsulated in that class, so clients of the class wouldn't have to worry about it. That's the kind of thing you need to think about when you start using concurrency.
Yes, multiple threads can read the same objects and are fine so long as other threads aren't modifying them at the same time. Depending on what you're doing the Fork-Join framework may be useful, it manages a lot of the threading details for you, so would be worth investigating.

Main method error in testing Stopwatch Object

I have an exercise that I am working on for programming class. I am getting an odd error that seems very basic, yet I am having trouble debugging it.
The code, when referenced, creates the standard StopWatch object with several instance methods associated with it. I created a main method at the bottom of the code in order to test each method in the StopWatch class to make sure it is working correctly.
Currently, when I run the program I get an error that says:
Exception in thread "main" java.lang.NoSuchMethodError: main.
I clearly have a main method in this class so I am not sure why I am getting this error.
The main method implements the Gambler's ruin program for testing. I am currently trying to test the stop() and elapsedTime() methods. The full code is enclosed below:
/* Notes:
* Start is the date of birth of the object. Most stopwatch don't keep track of when they were
* created.
*/
public class Stopwatch {
public long startTime; //The creation time of the stopwatch
public long totalTime; //Total time since watch was zeroed
boolean running = false; //This will flag if the watch is started or stopped
public Stopwatch() //First instance method called Stopwatch. What the client will use to create Stopwatch. This serves as the constructor.
{
start();
}
public void start()
{
startTime = System.currentTimeMillis();
running = true;
}
public void stop()
{
if(running) {
totalTime += System.currentTimeMillis() - startTime;
running = false;
}
}
public double elapsedTime()
{
if(running){
return System.currentTimeMillis() - startTime;
}
else{
return 0; //If the watch isn't currently running, return a 0 value.
}
}
public void zero()
{
totalTime = 0;
start();
}
public static void main(String[] args)
{
// Run T experiments that start with $stake and terminate on $0 or $goal.
Stopwatch program_time = new Stopwatch();
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int T = Integer.parseInt(args[2]);
int bets = 0;
int wins = 0;
for (int t = 0; t < T; t++)
{
// Run one experiment
int cash = stake;
while (cash > 0 && cash < goal)
{
// Simulate one bet.
bets = bets + 1;
if (Math.random() < 0.5)
{
cash = cash + 1;
}
else
{
cash = cash - 1;
}
} // Cash is either going to be at $0 (ruin) or $goal (win)
if (cash == goal)
{
wins = wins + 1;
}
}
System.out.println(100 * wins / T + "% wins");
System.out.println("Avg # bets: " + bets/T);
program_time.stop();
System.out.println(program_time.elapsedTime());
}
}
Any thoughts?
Check the file and class names -- they must match exactly, even with upper and lower case.
Check whether the Classpath is correct or not.

Categories