Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Threads are driving me crazy

Status
Not open for further replies.

yihyang

Programmer
Apr 4, 2013
1
0
0
US
The objective of these code is to create a very basic advertisement that prints every second. You get to enter a new message if you press enter at any time while it's blinking, and you exit the program if you input
"n" or "N".

The program works fine the first round, but in the subsequent loops for some FRACKIN reason
1. it knocks off the first letter of any input
(ex. input "announcement" prints as "nnouncement.. nnouncement..")
2. it prints the "Please enter..." statement AGAIN before it starts the Advertisement loops

Tis my first time here but any and all help would be soooo appreciated...

Here is the code:
// -------- Begin: Advertisement.java ------------
class Advertisement extends Thread
{
String msg = "";

public Advertisement(String str) {msg = str;}
public void run()
{
boolean cont = false;
if (!msg.equals("")) cont = true;
while(cont)
{
try
{
System.out.print(msg + ".. ");
sleep(1000);
}
catch (InterruptedException e)
{
break;
}
}
}
}
// --------End: Advertisement.java ------------
// -------- Begin: TestAdvt.java ------------
import java.io.*;

class TestAdvt
{
public static void main (String[] args)
{
try
{
String str = null;
do
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the advertisement message to be displayed (enter 'n' to exit):");
str = br.readLine();
if (str.equalsIgnoreCase("n")||str.equalsIgnoreCase("N")) break;
else{
Advertisement advt = new Advertisement(str);
advt.setDaemon(true);
advt.start();
System.in.read();
advt.interrupt();
}
} while(true);
}
catch (IOException e)
{
System.out.println("error: " + e.getMessage());
}
}
}
// --------End: TestAdvt.java ------------
 
My guess is that the System.in.read(); before the advt.interrupt(); is eating the first key stroke, but it's just a guess.

Btw, is you use equalsIgnoreCase you just need to check for n or N, not both

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top