| A Beginner:Why is my program always returning true? |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- Java Newbie questionHi all, I'm learning Java 2 by myself and find question for help.
I'm testing the System.in.read() method and tried the following program:
import java.io.*;
class ReadBytes {
public static void main(String args[])
throws IOException {
byte data[] = new byte[10];
System.out.println("Enter some characters.");
System.in.read(data);
System.out.print("You entered: ");
for (int i=0; i<data.length; i++) {
System.out.print((char)data[i]);
}
}
}
My question are:
(1) if I just comment out the "throws IOException" in the main, I
just got compilation error! Is the any condition I can tell whether
I have to throw something or not? I remembered in the HelloWOrld
app, I don't have to throw anything.
(2) If I entered more than 10 characters in the above test, I didn't
get overflow error. Why? Actually I'm expected an exception to
be caught.
Thanks in advance.
- 1
- Applet downloading from netI have a beginner's question.
If I go to internet, a web page containing a java applet. The applet
class
should be downloaded to my hardware.
Does anybody can tell me where I can find the downloaded applet class
file
and image file related to the applet class?
Thanks in advance,
P.Kaviarasu
email***@***.com
- 1
- 1
- Netbeans V5......Tomcat just won't start.. Why??My appologies if this is not the correct forum but I am desperate.
I have downloaded Netbeans V5.0 with JDK 1.5.0_05. Tomcat will not start.
It just seems to hang until it times out. If anyone else has had this
problem OR can direct me to a possible solution I would be deeply grateful.
PS Netbeans refuse to answer my emails!!
- 1
- 1
- Swing textboxes can't get focus after JFileChooserHi Java guru's,
I have a swing form that has a text field where a directory name can
be entered. Just to its right I have a button that will open the
JFileChooser dialog to allow selection of the directory name from a
dialog.
I can go in and type the directory name into the textbox by hand. So
far, so good.
I can go in and press the button, have the dialog appear, choose a
directory, and have the textbox programatically updated. Again, this
works.
But, if I press the button and choose a directory, I then lose the
ability to use my mouse to access any textboxes on my form. I am able
to use the tab button to move to, and update the textboxes.
I can't then click my mouse on a textbox and be able to enter in data.
Instead, I have to tab to it. The mouse also cannot be used to select
data within a textbox by double clicking or highlighting it. I CAN
hold down the mouse button and scroll right or left and have the
textbox's data shift if the text exceeds the width of the textbox.
But, the textbox appears to be disabled.
Interestingly enough, I AM able to use my mouse to click other BUTTONs
on the page.
So, its just the textboxes that seem affected.
Anyone have a solution or hints?
(btw, I'm using Java 1.4.2.x)
TIA
Here is my button listener:
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == btnRun)
if (areAllFieldsPopulated())
{
lblStatus.setText("Processing");
ExportFunctionalAreas exportFunctionalAreas = new
ExportFunctionalAreas();
exportFunctionalAreas.ExportXml(txtInputFileName.getText(),
txtOutputFileName.getText(), txtElementName.getText());
lblStatus.setText("Finished");
}
else
{
}
else if (event.getSource() == btnSelectFile)
txtInputFileName.setText(FileHandler.OpenFileDialog(txtInputFileName,"Open
Input File","xml","XML files (*.xml)"));
else if (event.getSource() == btnOutputDirectory)
txtOutputFileName.setText(FileHandler.OpenDirectoryDialog(txtOutputFileName));
}
and here is the open directory dialog code:
public static String OpenDirectoryDialog(Component Owner)
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(Owner))
return chooser.getSelectedFile().getPath();
else
return null;
}
- 4
- programi would to get the solution for the following program.
Write a complete Java program that does the following:
Prompt the user to type in the hour and minute departure time for an
airline flight.
Prompt the user to type in the hour and minute arrival time for that
flight. (Note: assume that the flight occurs in just one afternoon, leaving
at or after 1:00 and arriving at or before 12:59. Assume also that the user
provides valid input values!)
Calculate the total number of minutes the flight will be in the air.
Display the departure time, the arrival time, and the flight time (in
minutes) of the flight.
--
Message posted via http://www.javakb.com
- 4
- FreeBSD / Eclipse 3.1 / WTP 0.7Hello,
As port of Eclipse 3.1 is already available, I was trying to install Eclips=
e=20
WTP 0.7 to improve my work with JSPs and Servlets. I installed first: GEF,=
=20
EMF, and Java EMF Model Runtime: JEM-SDK-1.1.zip (this is the problem) from=
=20
WTP site, but I have still error saying that there is no such plugin as=20
org.eclipse.jem.util - I checked plugins directory and there is such plugin=
=20
installed, in manage configuration it is shown as disabled - that's probabl=
y=20
mean that this version is incompatible with FreeBSD.
Is there anybody who installed WTP with success on Free, and can share=20
his/her knowledge on this topic? Anybody work on porting JEM and WTP to=20
FreeBSD?
Best Regards,
Lee
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
- 6
- M-I'5.P ersecution - Capital Radi o - Chris T arrant-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
-= Capital Radio -. Chris Tarrant -=
-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
Capital Radio DJs have been "in on it" from the start.. One of the first
things. I heard in the summer of 1990 was from a Capital DJ who said, "If
he listens to Capital then he can't be all bad". (supportive, you see. We're
not bastards). Much. of what came over the radio in 1990 is now so far away
the precise details. have been obliterated by time. No diary was kept of the
details, and although archives if they. exist may give pointers, the
ambiguity of what broadcasters said would leave that open. to
re-interpretation.
In spring 1994, Chris Tarrant on his Capital morning show made an aside. to
someone else in the studio, about a person he didn't identify.. He said,
"You know this bloke? He says we're trying to kill him. We. should be done
for. attempted manslaughter".
That mirrored something I had said a day or. two before. What Tarrant said
was understood by the staff member in. the studio he was saying it to; they
said, "Oh no, don't say. that" to Tarrant. If any archives exist of the
morning show (probably unlikely) then. it could be found there; what he said
was so out of. context that he would be very hard put to find an explanation.
A couple of days later, someone at the site where I. was working repeated the
remark although. in a different way; they said there had been people in a
computer room when automatic fire. extinguishers went off and those people
were "thinking of suing. for attempted manslaughter".
Finally, this isn't confined to. the established radio stations. In 1990
after I had listened to. a pirate radio station in South London for about
half an hour, there was. an audible phone call in the background, followed
by total silence for a. few moments, then shrieks of laughter. "So what are
we supposed to say now?. Deadly torture? He's going to talk to us now, isn't
he?", which meant that they could. hear what I would say in my room.
5716
- 6
- How to get Cell ID from J2ME location API, on modern phones!Hi all, I wanted to know how to get the Cell ID using the J2ME
location API? I have found so much sites on the net bu they're all
since 2005 or 2003, and none of them contains a clear example (or even
basic idea) how to take the Cell ID. What I've tryed:
set the Criteria power management to low, so it doesn't search for
bluetooth. Everything else I've left as it is (now limits). It stops
the app for 60 secs (that's what I've set) and then it pops exception
- LocationException, which means it can't find info or timeout. I've
tested with longer times - same result. I'm sure the operator supports
it and the phone supports it (N73).
Please give an idea, please!
Thanks in advance...
- 8
- 11
- XML Validation From Flat File?Hi All,
I am trying to convert some Flat Files (Fixed-Width and CSV) to XML
files (Using Java) and I was wondering what is the best way to validate
the data in conversion time (in term and data type, size, missing
fields, etc.)? I know javax.xml.validation helps but is this the
easiest way? Is there any UI tool to help generating these Schema
files?
Thanks in Advance,
Homer
- 11
- Unreferenced enclosing class instance ?Hi,
I have below question about below enclosing class instance:
For below class
class MyOuter {
//.. say, some variables and methods defined here
class MyInner {
//.. say, some variables & methods defined here
}
}
pulic class TestNested {
public static void main(String[] args) {
MyOuter.MyInner inner = new MyOuter().new MyInner();
//.. suppose some time & memory consuming code executed afterwards
but inner not assigned 'null'
}
}
If compiled class TestNested ran & garbage collector did run at some
time before program terminated, will the MyOuter instance created in
first line of main be garbage collected ? Is there any method to
re-bind that created MyOuter instance with a reference variable after
the line "MyOuter.MyInner inner = new MyOuter().new MyInner();"
executed (besides split the statement into two like
MyOuter outer = new MyOuter();
MyOuter.MyInner inner = outer.new MyInner() ? :)
- 11
- Directory Aliases in ResinI recently had a project dropped into my lap that is written in JSP
running on Apache/Resin. A previous version of the application is
already running and configured on the production server, but new
functionality forces us to reconfigure some portions of both Apache
and Resin. There are basically two versions of the app that live in
separate directories, one that is served when someone goes to
www.domain.com, the second when someone goes to www.domain.com/subdir.
The main issue here is that there will be more than one "subdir", all
of which need to point to the same directory on the server, rather
than duplicating all the code for each new "subdir" that gets added.
Setting up aliases in Apache isn't a big deal, those are done. What
I'd really like to know is if it is even possible to set up aliases in
Resin similar to how they are done in Apache. I did some digging
through documentation, but was unable to find something. If anyone
can point me in the right direction, I'd appreciate it.
- 16
- Math.pow(a,b) Bug
--=-bch+Wpkq/6UBCHGw87bz
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
java.lang.Math.pow(a,b) incorrectly returns a positive value when a
negative value is raise to an odd integer. This occurs with the
jdk-1.4.2p6_4, which applies patchset 6. The attached file will
demonstrate the error.
The problem appears to be corrected by rebuilding the JVM with the
following correction:
--- e_pow.c.orig Mon Aug 30 21:01:45 2004
+++ e_pow.c Mon Aug 30 21:01:01 2004
@@ -173,7 +173,7 @@
}
/* (x<0)**(non-int) is NaN */
- if(((((u_int32_t)hx>>31)+1)|yisint)==0) return (x-x)/(x-x);
+ if(((((int32_t)hx>>31)+1)|yisint)==0) return (x-x)/(x-x);
/* |y| is huge */
if(iy>0x41e00000) { /* if |y| > 2**31 */
Furthermore, examining the experimental patchset, it appears that the
following patch also corrects the error:
2004-07-08 Thursday 20:09 glewis
* j2se/src/share/native/java/lang/fdlibm/src/e_pow.c:
. Merge in a fix recently added to FreeBSD's math library (taken
from
fdlibm-5.3):
"Fixed the sign of the result in some overflow and underflow cases
(ones
where the exponent is an odd integer and the base is negative)."
I've not yet run this through the compatibility test suite, so
this
change may be backed out if the suite relies on the broken
behaviour.
If I had the compatibility test suite, I would be willing to apply the
experimental patchset and perform the test. At the moment, I am not
willing to apply the patchset without being able to test the results.
Please email me with any questions or suggestions.
Best regards,
Tom H.
--
---------------------------------
-- Thomas M. Hermann
-- Thomas.Hermann AT cox DOT net
---------------------------------
--=-bch+Wpkq/6UBCHGw87bz
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
--=-bch+Wpkq/6UBCHGw87bz--
|
| Author |
Message |
Enteng

|
Posted: 2007-11-19 10:55:00 |
Top |
java-programmer, A Beginner:Why is my program always returning true?
Hi I'm learning Java and there seems to be something wrong with my
program. It's supposed to identify if the substring is in the main
string. My program always returns true and I'm a bit confused.
BTW, this is based from the tutorial from sun. I've read the whole
fundamentals section and try to re-write the examples there after a
while.
Anyway here's the code:
class findInString {
public static void main(String[] args){
String mainString = "The quick brown fox jumped over the lazy dog.";
String subString = "hey";
boolean isItThere = false;
int max = mainString.length();
Test:
for (int letter = 0; letter < max; letter++){
int subStringSize = subString.length();
int subStringCounter = 0;
int mainStringCounter = letter;
while (subStringSize-- > 0){
if (mainString.charAt(mainStringCounter) !=
subString.charAt(subStringCounter)){
continue Test;
}
}
isItThere = true;
break Test;
}
System.out.println(isItThere ? "Word found" : "Not found.");
}
}
If you guys see anything that I should improve on (my programming)
please feel free to comment. I'd appreciate them. Thanks!
|
| |
|
| |
 |
Arne Vajh鴍

|
Posted: 2007-11-19 11:03:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
> Hi I'm learning Java and there seems to be something wrong with my
> program. It's supposed to identify if the substring is in the main
> string. My program always returns true and I'm a bit confused.
>
> BTW, this is based from the tutorial from sun. I've read the whole
> fundamentals section and try to re-write the examples there after a
> while.
>
> Anyway here's the code:
>
> class findInString {
> public static void main(String[] args){
> String mainString = "The quick brown fox jumped over the lazy dog.";
> String subString = "hey";
> boolean isItThere = false;
>
> int max = mainString.length();
> Test:
> for (int letter = 0; letter < max; letter++){
> int subStringSize = subString.length();
> int subStringCounter = 0;
> int mainStringCounter = letter;
>
> while (subStringSize-- > 0){
> if (mainString.charAt(mainStringCounter) !=
> subString.charAt(subStringCounter)){
> continue Test;
> }
> }
>
> isItThere = true;
> break Test;
> }
>
> System.out.println(isItThere ? "Word found" : "Not found.");
> }
> }
>
> If you guys see anything that I should improve on (my programming)
> please feel free to comment. I'd appreciate them. Thanks!
class findInString {
public static void main(String[] args){
String mainString = "The quick brown fox jumped over the lazy
dog.";
String subString = "hey";
boolean isItThere = mainString.contains(subString);
System.out.println(isItThere ? "Word found" : "Not found.");
}
}
Arne
|
| |
|
| |
 |
Jeff Higgins

|
Posted: 2007-11-19 11:12:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
> Hi I'm learning Java and there seems to be something wrong with my
> program. It's supposed to identify if the substring is in the main
> string. My program always returns true and I'm a bit confused.
>
> BTW, this is based from the tutorial from sun. I've read the whole
> fundamentals section and try to re-write the examples there after a
> while.
>
> Anyway here's the code:
>
class findInString
{
public static void main(String[] args)
{
System.out.print(args[0].indexOf(args[1]));
}
}
>
>
> If you guys see anything that I should improve on (my programming)
> please feel free to comment. I'd appreciate them. Thanks!
|
| |
|
| |
 |
Patricia Shanahan

|
Posted: 2007-11-19 12:08:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
> Hi I'm learning Java and there seems to be something wrong with my
> program. It's supposed to identify if the substring is in the main
> string. My program always returns true and I'm a bit confused.
...
If the objective is to find out whether the substring is in the string,
just call the String method "contains".
However, if the objective is to learn more about programming, you should
debug this one.
I suggest using much shorter test strings. That way, you can work
through your code with paper and pencil.
Patricia
|
| |
|
| |
 |
Enteng

|
Posted: 2007-11-19 12:39:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
On Nov 19, 12:08 pm, Patricia Shanahan <email***@***.com> wrote:
> Enteng wrote:
> > Hi I'm learning Java and there seems to be something wrong with my
> > program. It's supposed to identify if the substring is in the main
> > string. My program always returns true and I'm a bit confused.
>
> ...
>
> If the objective is to find out whether the substring is in the string,
> just call the String method "contains".
>
> However, if the objective is to learn more about programming, you should
> debug this one.
>
> I suggest using much shorter test strings. That way, you can work
> through your code with paper and pencil.
>
> Patricia
Actually yeah, the objective is to learn more about programming.
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-11-19 14:29:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
On Sun, 18 Nov 2007 18:55:23 -0800 (PST), Enteng <email***@***.com>
wrote, quoted or indirectly quoted someone who said :
>while (subStringSize-- > 0){
> if (mainString.charAt(mainStringCounter) !=
>subString.charAt(subStringCounter)){
> continue Test;
> }
A few thoughts.
1. "continue" is almost never used in Java. You can usually get rid
of it by inverting the sense of your condition.
2. A loop must have something change each time around that has bearing
on when we quit. In this case what is changing? What are you TRYING to
compare with what?
3. code is easier to understand if you put "final" on any variable
that will not change its value later.
4. code is usually easier to understand if anything that is computed
in a loop that would give the same result every time around, should be
pulled out ahead of the loop and assigned to a final variable. The
simpler the innermost loop is, the easier the code is to understand
and the faster it will run.
5. Your code is missing the comments explaining what it is TRYING to
do. Without that, there is no way fix it.
6. if the assumption others made about "contains" is true, try your
code out with pencil and paper, or peppered with printouts to follow
it through step by step on a concrete example to see how it goes off
the rails.
I am being deliberately vague. I figure you will learn more from just
some hints that having the solution handed on a plate. I also get the
feeling you would rather sweat a bit.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
curt

|
Posted: 2007-11-19 14:34:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng <email***@***.com> wrote:
> Hi I'm learning Java and there seems to be something wrong with my
> program. It's supposed to identify if the substring is in the main
> string. My program always returns true and I'm a bit confused.
>
> BTW, this is based from the tutorial from sun. I've read the whole
> fundamentals section and try to re-write the examples there after a
> while.
>
> Anyway here's the code:
>
> class findInString {
> public static void main(String[] args){
> String mainString = "The quick brown fox jumped over the
> lazy dog."; String subString = "hey";
> boolean isItThere = false;
>
> int max = mainString.length();
> Test:
> for (int letter = 0; letter < max; letter++){
> int subStringSize = subString.length();
> int subStringCounter = 0;
> int mainStringCounter = letter;
>
> while (subStringSize-- > 0){
> if (mainString.charAt(mainStringCounter)
> != subString.charAt(subStringCounter)){
> continue Test;
> }
> }
>
> isItThere = true;
> break Test;
> }
>
> System.out.println(isItThere ? "Word found" : "Not
> found."); }
> }
>
> If you guys see anything that I should improve on (my programming)
> please feel free to comment. I'd appreciate them. Thanks!
As others have said, you just have a bug in the code. We all make mistakes
when we write code, and the one most important thing to learn, is how to
find bugs without help from others. Half of what a programmer must do is
remove bugs from code. There is nothing odd happening with the language,
your code simply isn't doing what you want it to do because you made a
simple mistake.
When code doesn't do what you expect it to do, look at it carefully and
think about what it's doing and you will normally be able to find the
problem.
You might try working backwards for example. If the program prints out
"Word found", then what does that tell you? It tells you that isItThere
must be true. So work backwards from that. How can isItThere be true?
There's only one place in the code it gets set to true, so you know it must
have been set there. Keep working backwards to see how that could have
happened.
When in doubt, add println() for every step of the code and look at the
100's of lines of output and see exactly what it's doing. That will allow
you to be sure all the statements in the code are doing what you expect
them to do, and it will allow you to see why the program is returning true.
You actually have 3 bugs in your code. If you fix the first two, you will
find the third rather quickly.
As far as general comments, here are a few to think about.
Try and keep the code as simple, and as concise as possible. Don't use
variables when you don't really need them, and use as short of name as is
reasonable for the scope of the variables. Variables with very limited
scope (like the index in a short loop) should have very short names, like 1
to 3 characters, local variables in a short method might be 3 to 5 letters
long. Arguments a big longer, and instance variables even longer.
If the variable names are too long, it makes it harder to "see" the code in
the middle of all the long and verbose variables. Here's a rewrite of your
code without changing the logic using shorter names. Maybe it will help
you see the error? I would suggest other changes, but I don't want to give
away what you bugs are until you find them on your own. :)
class findInString {
public static void main(String[] args){
String main = "The quick brown fox jumped over the lazy dog.";
String sub = "hey";
boolean found = false;
next:
for (int i = 0; i < main.length(); i++) {
int cnt = sub.length();
int s = 0;
int m = i;
while (cnt-- > 0) {
if (main.charAt(m) != sub.charAt(s))
continue next;
}
found = true;
break;
}
System.out.println(found ? "Word found" : "Not found.");
}
}
--
Curt Welch http://CurtWelch.Com/
email***@***.com http://NewsReader.Com/
|
| |
|
| |
 |
Enteng

|
Posted: 2007-11-19 23:20:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
On Nov 19, 2:33 pm, email***@***.com (Curt Welch) wrote:
> Enteng <email***@***.com> wrote:
> > Hi I'm learning Java and there seems to be something wrong with my
> > program. It's supposed to identify if the substring is in the main
> > string. My program always returns true and I'm a bit confused.
>
> > BTW, this is based from the tutorial from sun. I've read the whole
> > fundamentals section and try to re-write the examples there after a
> > while.
>
> > Anyway here's the code:
>
> > class findInString {
> > public static void main(String[] args){
> > String mainString = "The quick brown fox jumped over the
> > lazy dog."; String subString = "hey";
> > boolean isItThere = false;
>
> > int max = mainString.length();
> > Test:
> > for (int letter = 0; letter < max; letter++){
> > int subStringSize = subString.length();
> > int subStringCounter = 0;
> > int mainStringCounter = letter;
>
> > while (subStringSize-- > 0){
> > if (mainString.charAt(mainStringCounter)
> > != subString.charAt(subStringCounter)){
> > continue Test;
> > }
> > }
>
> > isItThere = true;
> > break Test;
> > }
>
> > System.out.println(isItThere ? "Word found" : "Not
> > found."); }
> > }
>
> > If you guys see anything that I should improve on (my programming)
> > please feel free to comment. I'd appreciate them. Thanks!
>
> As others have said, you just have a bug in the code. We all make mistakes
> when we write code, and the one most important thing to learn, is how to
> find bugs without help from others. Half of what a programmer must do is
> remove bugs from code. There is nothing odd happening with the language,
> your code simply isn't doing what you want it to do because you made a
> simple mistake.
>
> When code doesn't do what you expect it to do, look at it carefully and
> think about what it's doing and you will normally be able to find the
> problem.
>
> You might try working backwards for example. If the program prints out
> "Word found", then what does that tell you? It tells you that isItThere
> must be true. So work backwards from that. How can isItThere be true?
> There's only one place in the code it gets set to true, so you know it must
> have been set there. Keep working backwards to see how that could have
> happened.
>
> When in doubt, add println() for every step of the code and look at the
> 100's of lines of output and see exactly what it's doing. That will allow
> you to be sure all the statements in the code are doing what you expect
> them to do, and it will allow you to see why the program is returning true.
>
> You actually have 3 bugs in your code. If you fix the first two, you will
> find the third rather quickly.
>
> As far as general comments, here are a few to think about.
>
> Try and keep the code as simple, and as concise as possible. Don't use
> variables when you don't really need them, and use as short of name as is
> reasonable for the scope of the variables. Variables with very limited
> scope (like the index in a short loop) should have very short names, like 1
> to 3 characters, local variables in a short method might be 3 to 5 letters
> long. Arguments a big longer, and instance variables even longer.
>
> If the variable names are too long, it makes it harder to "see" the code in
> the middle of all the long and verbose variables. Here's a rewrite of your
> code without changing the logic using shorter names. Maybe it will help
> you see the error? I would suggest other changes, but I don't want to give
> away what you bugs are until you find them on your own. :)
>
> class findInString {
> public static void main(String[] args){
>
> String main = "The quick brown fox jumped over the lazy dog.";
> String sub = "hey";
> boolean found = false;
>
> next:
> for (int i = 0; i < main.length(); i++) {
> int cnt = sub.length();
> int s = 0;
> int m = i;
>
> while (cnt-- > 0) {
> if (main.charAt(m) != sub.charAt(s))
> continue next;
> }
>
> found = true;
> break;
> }
>
> System.out.println(found ? "Word found" : "Not found.");
> }
>
> }
>
> --
> Curt Welch http://CurtWelch.Com/
> email***@***.com http://NewsReader.Com/
Thanks for the comments and suggestions. I'm learning a lot :)
I thought giving variable detailed names would help me understand the
code better. Anyway I think I got it.
class findInString {
public static void main(String[] args){
String mainString = "The quick brown fox jumped over the lazy dog.";
String subString = "hey";
boolean isItThere = false;
int max = mainString.length();
Test:
for (int i = 0; i < max; i++){
int cnt = subString.length();
int s = 0;
int m = i;
while (cnt-- != 0){
if (mainString.charAt(m++) != subString.charAt(s++)){
continue Test;
}
}
isItThere = true;
break Test;
}
System.out.println(isItThere ? "Word found" : "Not found.");
}
}
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-19 23:33:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
> Thanks for the comments and suggestions. I'm learning a lot :)
> I thought giving variable detailed names would help me understand the
> code better. Anyway I think I got it.
>
> class findInString {
Class names should begin with an upper-case letter.
> public static void main(String[] args){
Do NOT use TAB characters in Usenet listings; use spaces to indent (2, 3, or 4
spaces per level).
> String mainString = "The quick brown fox jumped over the lazy dog.";
// "String" is not a good name part for variables.
// It ties the variable to the physical implementation too tightly.
> String subString = "hey";
> boolean isItThere = false;
> Test:
/*
Don't use labels to continue loops. 'continue' by itself is enough, or
better, follow Roedy's suggestion and invert the condition to eliminate the
'continue'. (And if you ask for advice, you should consider it before
rejecting it.)
*/
> for (int i = 0, max = mainString.length(); i < max; i++){
> int s = 0;
> int m = i;
>
for ( int cnt = subString.length(); cnt-- != 0 && ! isItThere; ){
if (mainString.charAt(m++) == subString.charAt(s++)){
isItThere = true;
> }
> }
> }
>
> System.out.println(isItThere ? "Word found" : "Not found.");
> }
> }
--
Lew
|
| |
|
| |
 |
Enteng

|
Posted: 2007-11-20 0:02:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
On Nov 19, 11:33 pm, Lew <email***@***.com> wrote:
> Enteng wrote:
> > Thanks for the comments and suggestions. I'm learning a lot :)
> > I thought giving variable detailed names would help me understand the
> > code better. Anyway I think I got it.
>
> > class findInString {
>
> Class names should begin with an upper-case letter.
>
> > public static void main(String[] args){
>
> Do NOT use TAB characters in Usenet listings; use spaces to indent (2, 3, or 4
> spaces per level).
>
> > String mainString = "The quick brown fox jumped over the lazy dog.";
>
> // "String" is not a good name part for variables.
> // It ties the variable to the physical implementation too tightly.
>
> > String subString = "hey";
> > boolean isItThere = false;
> > Test:
>
> /*
> Don't use labels to continue loops. 'continue' by itself is enough, or
> better, follow Roedy's suggestion and invert the condition to eliminate the
> 'continue'. (And if you ask for advice, you should consider it before
> rejecting it.)
> */
>
> > for (int i = 0, max = mainString.length(); i < max; i++){
> > int s = 0;
> > int m = i;
>
> for ( int cnt = subString.length(); cnt-- != 0 && ! isItThere; ){
> if (mainString.charAt(m++) == subString.charAt(s++)){
> isItThere = true;
>
> > }
> > }
> > }
>
> > System.out.println(isItThere ? "Word found" : "Not found.");
> > }
> > }
>
> --
> Lew
OK thanks I'll take note of that. About Roedy's suggestion I just
haven't tried some of it yet because I'm making this code while I'm on
the topic of labeled breaks (if that's what you're pertaining to about
rejecting advice). Actually it was one of his advices that made me
figure this out :) Lew, you sound offended or it's just the way you
give advice?
Honestly speaking it's kind of hard being criticized. I'm saying this
not because of your comments and suggestions(which are actually
helpful and I'm thankful for) but it's just that some comments are
well, discouraging. Don't get me wrong I appreciate all of them. Maybe
I'm just not used to this. Anyway I'm OT now, just voicing out :)
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-20 0:11:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
> Honestly speaking it's kind of hard being criticized. I'm saying this
> not because of your comments and suggestions(which are actually
> helpful and I'm thankful for) but it's just that some comments are
> well, discouraging. Don't get me wrong I appreciate all of them. Maybe
> I'm just not used to this. Anyway I'm OT now, just voicing out :)
I did not intend to criticize you. This is a discussion group; when something
that was mentioned was not answered, I suspected that it had been overlooked,
is all.
As for the detailed comments, those are all for your study and perusal. They
aren't criticisms, just comments.
I do not know why people have to take technical information personally. This
is a Java newsgroup where people make comments about Java code. That's life
here in the newsgroup. Get used to it.
--
Lew
|
| |
|
| |
 |
Patricia Shanahan

|
Posted: 2007-11-20 0:12:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng wrote:
...
> Thanks for the comments and suggestions. I'm learning a lot :)
> I thought giving variable detailed names would help me understand the
> code better. Anyway I think I got it.
...
I agree with many of the comments, but want to comment on a different
issue. In your code, you have a main method that does three jobs:
1. Define the tests case(s) to be run.
2. Report results of a test.
3. Do the actual search.
That structure makes it difficult to do multiple tests without editing
the program. Before doing anything to the algorithm, if it were my
program I would have done this refactoring:
public class FindInString {
public static void main(String[] args) {
test("The quick brown fox jumped over the lazy dog.",
"hey", false);
test("The quick brown fox jumped over the lazy dog.",
"", true);
test("The quick brown fox jumped over the lazy dog.",
"over", true);
test("The quick brown fox jumped over the lazy dog.",
"g. ", false);
}
private static void test(String mainString,
String subString, boolean expected) {
boolean isItThere = substringIsThere(mainString,
subString);
if (expected == isItThere) {
System.out.print("GOOD");
} else {
System.out.print("*BAD");
}
System.out.println(" " + isItThere + " |" + subString
+ "| |" + mainString + "|");
}
private static boolean substringIsThere(
String mainString, String subString) {
boolean isItThere;
isItThere = false;
int max = mainString.length();
Test: for (int i = 0; i < max; i++) {
int cnt = subString.length();
int s = 0;
int m = i;
while (cnt-- != 0) {
if (mainString.charAt(m++) != subString.charAt(s++)) {
continue Test;
}
}
isItThere = true;
break Test;
}
return isItThere;
}
}
In this organization, the main method just selects the tests to be run.
The test method does a single test. The "expected" parameter allows a
different print-out depending on whether the algorithm worked or not.
Finally, the substringIsThere method does nothing but find out whether
the substring appears in the string. Test cases can be added by
inserting "test" calls in main.
One of my test cases threw an exception. I put it in there because it is
the sort of thing that can go wrong in substring searches.
Patricia
|
| |
|
| |
 |
curt

|
Posted: 2007-11-20 4:38:00 |
Top |
java-programmer >> A Beginner:Why is my program always returning true?
Enteng <email***@***.com> wrote:
> On Nov 19, 2:33 pm, email***@***.com (Curt Welch) wrote:
> Thanks for the comments and suggestions. I'm learning a lot :)
> I thought giving variable detailed names would help me understand the
> code better.
Yes, variable names are a real mater of personal taste. Maybe the ones you
used work better for how you think about your code. I just wanted to give
you something else to think about.
> Anyway I think I got it.
Yes, much better. You found 2 of the 3 bugs I mentioned.
Try:
subString = ".blowup";
and see what happens to find the third bug.
Now that you found the basic bugs, I'll add a few more comments you can
think about.
> class findInString {
> public static void main(String[] args){
> String mainString = "The quick brown fox jumped over the
> lazy dog."; String subString = "hey";
> boolean isItThere = false;
>
> int max = mainString.length();
> Test:
You should generally avoid labeled loops. It's a sign your code is too
complex and you should try to restructure it to make it simpler. Complex
code tends to have hidden bugs in it - as yours does.
Though from your other message, it seems you were using this example as a
place where you can use labeled loops - so that's fine for learning how to
do these things. This is a perfect example of where labeled loops are
needed.
> for (int i = 0; i < max; i++){
> int cnt = subString.length();
> int s = 0;
> int m = i;
>
> while (cnt-- != 0){
This loop needs to scan increasingly higher indexes in the two strings yet
you use a loop variable that's counting down. That's highly counter
intuitive to me.
The outer loop needs to scan forward as well, but yet you used a downward
counting variable there. Why did you use two different style loops to do
the same basic thing?
In general, loops that count down are much harder to understand than loops
that count up. Try not to use them unless you actually need to count down.
> if (mainString.charAt(m++) !=
> subString.charAt(s++)){
Inside your loop, you needed two variables (m and s) to count up. You
didn't need cnt to count down. This is, cnt wasn't used at all inside the
loop. When you need a variable to change inside a loop, it's best to try
and make that variable the one which is controlling the loop.
The way you wrote it, you ended up with three variables changing in this
inner loop. You only needed one to change. The fact that you wrote it so
that three changed at once, only increased the odds that you would make a
mistake and not change all three at once. It's like trying to keep track
of a 3 ring circus - it's hard to do and easy to miss something - as you
did. It only gets worse when you are dealing with much larger and much
more complex code.
> continue Test;
> }
> }
>
> isItThere = true;
> break Test;
I removed the "test" from that break because it wasn't needed. If I see a
labeled break in code, it makes me assume the label was needed, so I assume
it must be breaking out of multiple layers - which would mean, if the rest
of the code was off the screen (which it is for me at this point because of
my comments) I would assume that break was breaking out more than just the
following }:
> }
>
> System.out.println(isItThere ? "Word found" : "Not
> found."); }
> }
Here's a simple rewrite to clean up the loops (without fixing your final
bug):
Test:
for (int m = 0; m < main.length(); m++) {
for (int s = 0; s < sub.length(); s++) {
if (main.charAt(m+s) != sub.charAt(s))
continue Test;
}
isItThere = true;
break;
}
See how much simpler it becomes when you use only one variable in the inner
loop instead of three? You used 5 loop control variables, and I only used
2. I used the exact same loop structure for both loops, so it's easier to
understand what the second loop is doing after you figure out what the
first loop is doing. Maybe this rewrite will help you see the final bug as
well?
Note that I again put the mainString.length() inside the for loop instead
of using the max variable. For efficiency, it can be wise to use a
variable instead of calling a method for every test of the loop. But the
goal here is always clear bug-free code first, and efficiency second. You
should only sacrifice clear code for efficiency when you are fairly sure
efficiency is going to be an issue.
If the length() method had to scan the string and count the bytes, then
calling it every time in a loop is an efficiency issue. But java strings
don't work that way. They know their length - it's stored in them. So the
length() method is just a simple getter method - once which, for all I
know, might be optimized away by the compiler as a final method and turned
into a direct access of the length of the string. So the efficiency saved
by using the max variable in this case is minimal.
There's also the issue that the test condition might for some loops, be
changing in the loop. And in general, most loops are less likely to have
bugs if you put the end condition test in the loop, instead of caching it
in a variable like "max" and using the saved value. For example, if you
are scanning a list where elements can be removed from the list as you
scan, you will need to test the current size of the list for each iteration
of the loop instead of using the max variable. I you use a max variable,
you are more likely to have a bug in your code. So as a rule, only use
variables for efficiency like that when you are fairly sure the efficiency
will be important for your application.
But again, this is really a style issue on whether you use the max variable
or put the method call in the loop. I think the gain in simplicity is well
worth the minor loss in efficiency.
There are many ways to rewrite this to get rid of the Test: label. Many
rewrites however only make it more complex and I think the real goal should
always be to make the code as simple and clear as possible. A code with a
bug in it that blows up when it's in production is far far worse, than any
code style issue, but keeping the code as simple as possible, is what helps
us make sure there are no bugs in our code.
Lew suggested one rewrite, but he didn't look at the code long enough to
figure out what you were doing because his rewrite isn't even close to
working - it blows up with an exception even more than yours does. Lew is
normally better than that. :)
Here's one way to rewrite and remove the loop label:
for (int m = 0; m < mainString.length(); m++) {
int matchCnt = 0;
for (int s = 0; s < subString.length(); s++) {
if (mainString.charAt(m+s) == subString.charAt(s))
matchCnt++;
else
break;
}
if (matchCnt == subString.length()) {
isItThere = true;
break;
}
}
I don't think that makes the code better - I think it makes it more complex
and more bug prone (I've not tested the above code so there's a good chance
it has a bug in it :)).
The way I like to clean up code that gets too complex like that it to use
the power of a return statement. You break it up into separate methods and
keep the work of each method simpler (this code has your bug in it as
well):
// is sub located anywhere in main?
boolean contains(String main, String sub)
{
for (int o = 0; o < main.legnth(); o++) {
if (match(main, o, sub))
return true;
}
return false;
}
// Is sub located in main at offset?
boolean match(String main, int offset, String sub)
{
for (int i = 0; i < sub.length(); i++) {
if (main.charAt(i+offset) != sub.charAt(i))
return false;
}
return true;
}
(I didn't compile or test the above so it could have bugs - other than the
one from your code)
The power of the return statement replaced the "continue Test" from your
code. In general, we use return so much we are very used to what it does
and how it works, where as you almost never see a labeled loop in code
(I've yet to see my first example of it in real Java code).
It's very common in OO code to break your code into many tiny methods like
this where each one only does one very simple task. This makes it easier
for the programmer to be sure the method is doing the task correctly. The
simpler the task of the method, the more likely you will get the code
right. When you try to do multiple tasks in one method, you increase the
odds that you will make a mistake and not see an error.
When we are being lazy, or when we are in a hurry, we will not take the
time to restructure our code to make it clean, we will just keep adding and
adding crap to a method which is already way too larger because it's easier
to add a few lines, than it is to refracture into a simpler and cleaner
design. But doing that will always come back to bite you with a bug you
didn't catch that you never should have let get past you.
I constantly rewrite my code to see if I can find a better way to express
the algorithm. Learning the simplest way to write the code takes time and
practice. It's all part of the art of programming. It's one thing to be
smart enough to make the code work no matter how it's structured. It's
another thing to be able to simplify the code so you can look at it and
know its right without having to test it to death. You can't test quality
into the code.
--
Curt Welch http://CurtWelch.Com/
email***@***.com http://NewsReader.Com/
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- FileOutputStream to Different DirectoryHello,
I'm trying to get Java to create a file in a new directory (which
already exists). Using FileOutputStream, I've been able to create a
new file, but it always puts it into the same directory (as far as I
can tell, there is only one argument for file name... nothing for
path). Is there some way to specify another path?
Thanks,
Ben
- 2
- [java.nio] Blocking mode for a while - How ?I'm using selector to manage connection on server. When server get an
incomming connection register this connection in non-blocking mode for
making readiness selection on it. In some moment i want to operate
with clients channels with blocking mode... but i can't change channel
to blocking mode, because is registered with selector in non-blocking
mode - i get IllegalBlockingModeException. How can i operate for a
while in blocking mode, but not to lose possibility readiness
selection on channel?
--
pozdr.;)
~xEM
- 3
- Using Java CORBA under OS2Hi,
OS/2 (y'all remember that, right? It's now out in a spiffy new independent
version http://www.ecomstation.com) uses DSOM, which is a relative of CORBA
to define objects at the OS-level. I am wondering if there are any tools to
take classes defined in CORBA then implemented in Java and use them under
OS/2. It could work really nicely. I found an old SOM to Java compiler from
IBM, but that seems to be unsupported now.
Just wondering if anyone has experience with this.
-- jjg
There are no z's in my address.
- 4
- Set colum width in a JTablePosted this on comp.lang.java.programmer before seeing this group - sorry.
Hi,
I'm trying to set the column width in a JTable.
This only works on the first column.
As soon as I use setMinWidth() or setMaxWidth() on the second or third
column setPreferredWidth() wont't work at all.
I use this funtion:
public void insertHead(String headName, int width)
{
TableColumn column = new TableColumn();
column.setHeaderValue(headName);
columnModel.addColumn(column);
column.setMinWidth(15);
column.setMaxWidth(200);
column.setPreferredWidth(width);
}
The JTable is set to AUTO_RESIZE_SUBSEQUENT_COLUMNS.
Any hints?
Thanks.
Rene
- 5
- JSP EL and explicit error messagesHi,
I sometimes mistype object and property names in JSP EL expressions,
and find that no error is generated. It just doesn't evaluate the
expression.
For example, for an object named foo with a property of name, this
would throw an error:
<%= foo.getNAme() %>
where this won't:
${foo.nAme}
Is there any way to make it produce explicit errors in a case like this?
- 6
- ports/Javamail-1.3.2 updateHi!
My name is T.Tamura (DAIGU)
I found javamail's update.
So, It's easy to change Ports/java/javamail.
Please use, if very well.
============= BEGIN ==================================
diff javamail/Makefile javamail132/Makefile
9c9
< PORTVERSION= 1.3.1
---
> PORTVERSION= 1.3.2
13c13
< DISTNAME= ${PORTNAME}-${PORTVERSION:S/./_/g}-upd
---
> DISTNAME= ${PORTNAME}-${PORTVERSION:S/./_/g}
26c26
< DOWNLOAD_URL= http://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=7515-java_mail-1.3.1-oth-JPR&SiteId=JSC&TransactionId=noreg
---
> DOWNLOAD_URL= http://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=7515-java_mail-1.3.2-oth-JPR&SiteId=JSC&TransactionId=noreg
diff javamail/distinfo javamail132/distinfo
1,2c1,3
< MD5 (javamail-1_3_1-upd.zip) = a83fa4102e7a1441d7c1046015675f46
< SIZE (javamail-1_3_1-upd.zip) = 2270699
---
> MD5 (javamail-1_3_2.zip) = e65b92fde398f472cbe4cb12c69303fe
> SIZE (javamail-1_3_2.zip) = 2348764
>
Only in javamail132: work
============== END ===================================
- 7
- Jars and getResource()Hi there,
I've been trying to find a solution to this with no luck so far.
Consider a project with the following dir structure
/bin
/resources
/resources/velocity
.
.
etc.
In /resources/velocity there is a file "velocity.properties"
with /resources/velocity in the classpath I can simply say from within a
class
Class.class.getResourceAsStream(/velocity.properties);
and get an InputStream to that file.
However, when packaging it in a jar file, the above statement stops
working even if in the Manifest I specify in the header:
Class-Path: resources/velocity/
Any ideas? :(
TIA
- 8
- java.security.PrivilegedActionExceptionI am accessing a JAXM based Web Service, deployed in Tomcat under
JWSDP.
However I am getting an exception like this:
java.io.IOException: java.security.PrivilegedActionException:
com.sun.xml.messaging.saaj.SOAPExceptionImpl:
Any Suggestions Please...
- 9
- Java Compare datesHi,
I have a date (only hours:minutes:seconds) in a text file against
which i need to compare the current time.
The date in the text file is expressed in GMT.
How do i compare and compute the difference (i am only interested in
the hours,minutes and seconds)?
The only way looks like, creating a new Date/Calendar object from the
hh:mm:ss and setting the day, month and year from a new instance of
Date/Calendar and then computing the difference.
This could run into issues when we are in the next day while GMT is
still "yesterday" during which this computation would fail.
Are there other ways to do that?
Appreciate any assistance.
Thanks,
Manglu
- 10
- SpinnerNumberModel question (maybe JSpinner..)Hi!
I have an application with quite a few jspinners with the default
spinnernumbermodel (i.e created with JSpinner myspinner=new
JSpinner(new SpinnerNumberModel(val,min,max,step));)
Anyway, say I put the allowed range to be 0-10.
Can I notify the user that they typed in an invalid value then?
that is the user types in 100, the spinner will reject this when the
user select the next spinner, but I would like to inform the user that
they tried to enter an illegal value. Can this be done in an efficent
way?
regards
Daniel
- 11
- Finding out which thread has interrupted Thread th = Thread.currentThread();
try {
th.sleep(10000);
} catch (InterruptedException e) {
/* I want to know *which* thread interrupted this one. */
}
How can I achieve this?
Tnx.
Manish
--
http://mannu.livejournal.com/
- 12
- 13
- Confused with PrintWriter, OutputStream and OutputStreamWriter.Hello
Rather confused with PrintWriter, OutputStream and OutputStreamWriter.
Not sure how to pass osw to pw.
PrintWriter pw=getAgentOutput();
RichTextItem body = (RichTextItem) docRT.getFirstItem("RTItem");
OutputStreamWriter osw = new OutputStreamWriter( new
RichTextOutputStream(body, true, true) );
Want print the contents of osw rich is a RichText to pw so as to do
println.
Or is there a better way to parse the richtext?
Many thanks
- 14
- Check out my Java appletI have developed a Java applet that lets you run and manage a website
online.
I would like to see how well it runs on your browser. You can edit the page
right in there, but cannot save without access to my server.
A website does not need the server to support any scripting technology or a
database to host this. Everything is done inside the browser.
regards,
Linh.
- 15
- Substitute for Tiles in JSF?Hello
I am working on a refactor. The project handles some trather stright
forward business, but the previous authors decided to use a best of
breed or so they thought amalgam of frameworks. They used Spring,
Struts Tiles Hibernate and JSF. The trouble is new people coming to
the project need to spend weeks coming up to speed on all the open
source technologies. So I am endeavoring to reduce the number of
frameworks I want to keep JSF as I see this as the future of Web
development. Hibernate I believe we may keep.
Spring is easy to get rid of just use the JSF controller. But tiles!
should we use a frameset or use JSP includes? Or does someone know of
a Set of JSF controls that can replace Tiles? Facelets seems a bit of
overkill.
Suggestions any one?
Bob
|
|
|