How to repeat main method in java - repeat

My question is simple but the answer eludes me. I have looked up and down for this little bit of info and can't find it.
It's simple, I have a program with println text that I want to have repeated just once. what is the line of code to do this in the simplest way.
There are two lines of System.out.println that make up the static void main and I want it to just repeat itself just once so that there is double without me actually typing in a System.out.println() to put a space between the first set and then just typing in an exact copy of the first set of two lines.
Example:
System.out.println("Hello World!");
System.out.println("I am Klinton");
System.out.println()
System.out.println("Hello World!");
System.out.println("I am Klinton");
I want to shrink this to just the first two lines and have the program repeat it once to achieve the same result.

Use a for loop.
for(int i=1; i<=10; i++)
{
System.out.println("Hello World!");
System.out.println("I am Klinton");
System.out.println()
}
This will loop ten times. It starts at one with initializing a new variable i to 1, sets the termination to when I is no longer less than or equal to 10, and the increment to 1, so i will increase by 1 each time the loop runs..

Related

java program for printing the two largest numbers a user inputs

Whenever I run my compiled code, it displays the largest number but it doesn't display the second largest number correctly. Here is my code:
package twoLargestNumbers;
import java.util.Scanner;
//find two largest numbers
public class twoLargestNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int num;
int counter=0;
int largest=0;//largest
int second=0;//second largest
System.out.println("Enter number:");
num=input.nextInt();
while(counter<5){
num=input.nextInt();
if(num>largest){
second=largest;//store largest to second largest
largest=num;//store largest to inputted number
}
else{
if(num>second)
second=num;//store second number to inputed number
}
counter=counter+1;
}
System.out.println("largest number is "+largest);
System.out.println("and second largest number is "+second);
}
}
What am I doing wrong? I reread and read this code and I cannot find out what the error is.
Remove the num=input.nextInt() before the while loop starts.
The initial input is being called and then straight away after the "first" input in the while method is called.
A couple of other tips, usually for a defined length of loop (in this case, 5) you would use a for loop to show your intent a bit more.
Also you can increment counter doing: counter++; or counter += 1;
Assuming the intent of your program is to ask for 5 numbers of input and then display the largest two, that should all help. Hope it did.
Also I don't think this block of code is needed, the second largest is already being stored in the first if statement.
else{
if(num>second)
second=num;//store second number to inputed number
}

Looping in OpenGL with glutTimerFunc(...)

I want to create a program that draws some objects to scene using OpenGL, where I am continually changing the position of those object manually. To achieve this, I need to run some kind of loop where on each loop, it changes the position of the objects, and then draws to the screen, before repeating.
Given that glutMainLoop() is a non-returning function, and is also compulsory to run an OpenGL program, I need to run my loop with some sort of timer.
Now my solution which works is similar to the following:
void Render()
{
// Draw some objects using OpenGL
// ......
// ......
}
void Loop
{
// Update the positions of the objects
// ......
// ......
glutPostRedisplay();
glutTimerFunc(1, Loop, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
GlutCreateWindow("Test");
glutDisplayFunc(Render);
glutMainLoop();
glutTimerFunc(1, Loop, 0);
}
However, I am not sure I understand why there is the need for the glutTimerFunc() call in main(). Why can I not just replace it with a direct call to Loop()?
For example:
int main(int argc, char** argv)
{
glutInit(&argc, argv);
GlutCreateWindow("Test");
glutDisplayFunc(Render);
glutMainLoop();
Loop();
}
This does not work. The objects do not move on the screen as expected, and furthermore, then OpenGL window is totally unresponsive; I cannot even close it by clocking the cross on the title bar.
Surely glutTimerFunc(1, Loop, 0); just calls Loop() in the same way I have done in the second example, so why does this not work...?
Basically, the glutTimerFunc waits for a number of milliseconds to pass before calling the callback (in your case, Loop()). In this way it acts like a refresh operation.
Check out →GLUT API for more detail
void glutTimerFunc(unsigned int numMilliseconds, functionCallback, value);
So, that means you can pass in something like this:
glutTimerFunc(1000 / SCREEN_FPS, Loop, 0);
For extra info on main loops
deWitter's Gameloop
However, as your project gets more complex, you might find that you want the objects in your scenes rendering at constant speed. In addition to the glutTmerFunc, you can make you animations work with elapsed time - found by calculating the difference between the current time and previously current time.
Hope this helps!
Here's a really simple glutTimerFunc() example from a real program.
I wanted to hi-jack the title bar for command input. When you typed stuff, it appeared in the title bar and when you pressed return, it executed the command. I wanted a blinking cursor.
char title[80]; // This is where our keystrokes go.
char * cursor = NULL; // This points to the cursor character.
void cursorBlink(int id) {
if (cursor) {
*cursor = (*cursor == ' ') ? '_' : ' ';
glutSetWindowTitle(title);
glutTimerFunc(1000.0, cursorBlink, 0);
}
}
This isn't quite the whole thing. The ESC key gets us into command line entry mode. This sets up the title string and the cursor pointer, and it also has to make the first call to cursorBlink() to get the loop started. When command entry is done, the cursor point gets set back to NULL, and the loop shuts itself down.
The cursorBlink argument is not used. This is common with simple animations. Don't worry about it.

remove objects from arraylist is doing strange things

In the code below, i want the balls to change from ArrayList ballList to another ArrayList oldBalls as soon as their age turns higher than a threshold value.
This code should be very simple but i can't figure out why when the age is same as the threshold (not larger) they disappear and then they come back 2 frames later.
I have checked related questions using iterators for ArrayLists in java but i think there should be a way to do this in processing without java.
Also i cant seem to post any question on the processing forum even though i can sign in, no idea why...
I have reduced the code to the minimum able to reproduce the error.
ArrayList <Ball> ballList;
ArrayList <Ball> oldBalls;
int threshold=4;
PFont font;
void setup(){
size(400,400);
frameRate(0.5);
font=createFont("Georgia", 18);
textFont(font);
textAlign(CENTER, CENTER);
ballList=new ArrayList<Ball>();
oldBalls=new ArrayList<Ball>();
noFill();
strokeWeight(2);
}
void draw(){
background(0);
Ball b=new Ball(new PVector(10, random(height/10,9*height/10)),new PVector(10,0),0);
ballList.add(b);
stroke(0,0,200);
for(int i=0;i<oldBalls.size();i++){
Ball bb=oldBalls.get(i);
bb.update();
bb.render();
text(bb.age,bb.pos.x,bb.pos.y);
}
stroke(200,0,0);
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
}
class Ball{
PVector pos;
PVector vel;
int age;
Ball(PVector _pos, PVector _vel, int _age){
pos=_pos;
vel=_vel;
age=_age;
}
void migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
}
}
void update(){
pos.add(vel);
age+=1;
}
void render(){
ellipse(pos.x,pos.y,24,24);
}
}
Note how balls labelled with age=threshold suddenly disappear...
i guess the problem is here:
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
//add this
if(bb.migrate())
i--;
text(bb.age,bb.pos.x,bb.pos.y);
}
and
boolean migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
//and this
return true;
}
return false;
}
migrate() will remove the object from the ballList and reduce it's size by 1.
What it looks like is happening here is because you're altering the List's whilst iterating through them. Consider this for loop you have here
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
Say ballList has 2 balls in it both age 3, the first loops gets ball[0] and then removes it from the list, i will increment and the loop will immediately exit because ballList.size() is now 1. So it's not the ball which gets to age 4 that vanishes but the subsequent one.

How to detect that a thread has started using javassist?

I have to instrument any given code (without directly changing given code ) at the beginning and end of every thread. Simply speaking , how can I print something at entry and exit points of any thread.
How can I do that using javassist ?
Short Answer
You can do this by creating an ExprEditor and use it to modify MethodCalls that match with start and join of thread objects.
(very) Long answer (with code)
Before we start just let me say that you shouldn't be intimidated by the long post, most of it is just code and once you break things down it's pretty easy to understand!
Let's get busy then...
Imagine you have the following dummy code:
public class GuineaPig {
public void test() throws InterruptedException {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(i);
}
});
t.start();
System.out.println("Sleeping 10 seconds");
Thread.sleep(10 * 1000);
System.out.println("Done joining thread");
t.join();
}
}
When you run this code doing
new GuineaPig().test();
You get an output like (the sleeping system.out may show up in the middle of the count since it runs in the main thread):
Sleeping 10 seconds
0
1
2
3
4
5
6
7
8
9
Done joining thread
Our objective is to create a code injector that will make the output change for the following:
Detected thread starting with id: 10
Sleeping 10 seconds
0
1
2
3
4
5
6
7
8
9
Done joining thread
Detected thread joining with id: 10
We are a bit limited on what we can do, but we are able to inject code and access the thread reference. Hopefully this will be enough for you, if not we can still try to discuss that a bit more.
With all this ideas in mind we create the following injector:
ClassPool classPool = ClassPool.getDefault();
CtClass guineaPigCtClass = classPool.get(GuineaPig.class.getName());
guineaPigCtClass.instrument(new ExprEditor() {
#Override
public void edit(MethodCall m) throws CannotCompileException {
CtMethod method = null;
try {
method = m.getMethod();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String classname = method.getDeclaringClass().getName();
String methodName = method.getName();
if (classname.equals(Thread.class.getName())
&& methodName.equals("start")) {
m.replace("{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } ");
} else if (classname.equals(Thread.class.getName())
&& methodName.equals("join")) {
m.replace("{ System.out.println(\"Detected thread joining with id: \" + ((Thread)$0).getId()); $proceed($$); } ");
}
}
});
guineaPigCtClass
.writeFile("<Your root directory with the class files>");
}
So what's happening in this small nifty piece of code? We use an ExprEdit to instrument our GuineaPig class (without doing any harm to it!) and intercept all method calls.
When we intercept a method call, we first check if the declaring class of the method is a Thread class, if that's the case it means we are invoking a method in a Thread object. We then proceed to check if it's one of the two particular methods start and join.
When one of those two cases happen, we use the javassist highlevel API to do a code replacement. The replacement is easy to spot in the code, the actual code provided is where it might be a bit tricky so let's split one of those lines, let's take for example the line that will detect a Thread starting:
{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } "
First all the code is inside curly brackets, otherwise javassist won't accept it
Then you have a System.out that references a $0. $0 is a special parameter that can be used in javassist code manipulations and represents the target object of the method call, in this case we know for sure it will be a Thread.
$proceed($$) This probably is the trickiest instruction if you're not familiar with javassist since it's all javassist special sugar and no java at all. $proceed is the way you have to reference the actual method call you are processing and $$ references to the full argument list passed to the method call. In this particular case start and join both will have this list empty, nevertheless I think it's better to keep this information.
You can read more about this special operators in Javassist tutorial, section 4.2 Altering a Method Body (search for MethodCall subsection, sorry there's no anchor for that sub-section)
Finally after all this kung fu we write the bytecode of our ctClass into the class folder (so it overwrites the existing GuinePig.class file) and when we execute it... voila, the output is now what we wanted :-)
Just a final warning, keep in mind that this injector is pretty simple and does not check if the class has already been injected so you can end up with multiple injections.

sprintf() and WriteFile() affecting string Buffer

I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:
1) read a byte from the serial port
2) store each char into tagBuffer as they are read
3) run a query using tagBuffer to see what type of tag it is (book or shelf tag)
4) depending on the type of tag, output a series of bytes corresponding to the type of tag
Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.
The lines are the two lines at the very bottom:
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().
I thought sprintf and WriteFile are I/O functions and would have no effect on variables.
I'm stuck and I need help to fix this.
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= PACKET_LENGTH )
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if( str == "book" )
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
With those two lines, my output looks like this:
s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001
Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.
Any help at all will be greatly appreciated. Thanks.
Where are you allocating tagbuffer, how large is it?
It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.
It seems unlikely that those two lines would have that effect on a correct program - maybe you haven't allocated sufficient space in buf for the whole length of the string in tagBuffer? This might cause a buffer overrun that is disguising the real problem?
The first thing I'd say is a piece of general advice: bugs aren't always where you think they are. If you've got something going on that doesn't seem to make sense, it often means that your assumptions somewhere else are wrong.
Here, it does seem very unlikely that an sprintf() and a WriteFile() will change the state of the "buf" array variable. However, those two lines of test code do write to "hSerial", while your main loop also reads from "hSerial". That sounds like a recipie for changing the behaviour of your program.
Suggestion: Change your lines of debugging output to store the output somewhere else: to a dialog box, or to a log file, or similar. Debugging output should generally not go to files used in the core logic, as that's too likely to change how the core logic behaves.
In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:
Serial Port I/O from Joseph Newcomer's website.
Serial Communications in Win32 from MSDN.
In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.
This may sound more complex than your current design, but really it isn't, as Newcomer explains.
I hope this helps!