Why is this loop bad practice? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The following loop is not good practice. Is it due to a String being the main condition of the for loop rather than an int variable, meaning the for loop is infinite? Also, is it due to there being no instance to enter 'end' to stop the loop?
Scanner in = new Scanner(System.in);
int i = 0;
for (String s = in.next(); !s.equals("end"); i++)
{
System.out.println("The value of i is: " + i + " and you entered " + s);
}
How can I rewrite it, so that it conforms to accepted style?
(This is a question in a past exam paper.)

Well your string s is never changing, which can lead to an infinite loop. You probably wanted:
for (String s = in.next(); !s.equals("end"); s = in.next(), i++) {
...
}
Some (me included) might say that i++ shouldn't be in the increment section of this loop, since it's not directly relevant to the condition:
for (String s = in.next(); !s.equals("end"); s = in.next()) {
...
i++;
}
Is it due to a string being the main condition of the for loop rather than an int variable, meaning the for loop is infinite?
The original loop was indeed infinite (at least, after an initial input is entered and assuming "end" wasn't the first input). However, it's not for the reason you state. For-loops are most commonly written using integral loop control variables, but it's not always the case. For example, a common idiom for iterating through a linked list is:
for (Node node = list.head; node != null; node = node.next) {
...
}
The problem with your loop is that the string s is never changed, so it will never equal "end" unless that's the first input.

I would suggest separating the looping condition and the call to Scannner.next():
while (in.hasNext()) {
String s = in.next();
if (s.equals("end")) {
break;
}
System.out.println("The value of i is: " + i + " and you entered " + s);
i++;
}
I think this is much easier to understand than trying to squeeze everything into a for expression.

There are multiple problems with this code:
s never changes after the initial assignment, so it's an infinite loop.
Calling .next() could throw NoSuchElementException or IllegalStateException. Rather than catching these exceptions, I consider it more polite to check .hasNext() beforehand, since running out of input is a foreseeable rather than an exceptional situation. However, the alternative ask-for-forgiveness style could also be acceptable.
The for-loop header does not form a coherent story — it initializes s and tests s, but updates i.
In my opinion, System.out.format() would be slightly more preferable to System.out.println() with concatenation.
I would write it as:
Scanner in = new Scanner(System.in);
int i = 0;
String s;
while (in.hasNext() && !"end".equals(s = in.next())) {
System.out.format("The value of i is: %d and you entered %s\n", i++, s);
}
It might also be a nice user interface touch to tell the user that end is a magic word to terminate the loop (assuming it were modified to work as probably intended).

The common practice with for loops is that the counter variable is repeated in each term:
for(int i=...; i<... ; i++)
In the example above, the code mixes variables. Which is confusing to the reader and probably lead to the bug that the loop only terminates if you input end as the first value.

This loop is a bad idea, because you're taking setting s once from the user input and not in every iteration.
Thus, it will cause you to run infinite time in case s was filled with value different from "end".
You probably wanted something more like this:
for (String s; (s = in.nextLine()).equals("end"); i++)
{
System.out.println("The value of i is: " + i + " and you entered " + s);
}

This isn't a good idea because the string s may never equal "end". You'll probably want to check if the scanner has another string. Also, you only initialize the string to in.next() but you need to set s to the next string after each iteration of the loop.
while(in.hasNext()) {
String s = in.next();
if (s.equals("end")) {
break;
}
// ..
}

This approach is too bad.
The Given Code :-
Scanner in = new Scanner(System.in);
int i = 0;
for (String s = in.next(); !s.equals("end"); i++)
{
System.out.println("The value of i is: " + i + " and you entered " + s);
}
The 1st part of for loop only execute once in life.
String s = in.next() //Execute only once in life
The 2nd part of this for loop never be true , because the input console will never allow to enter the 2nd input.
!s.equals("end")//2nd part
This program will never allow to enter 2nd input from console, because the in.next() will execute only once.And the exit token for this loop is "end" which is not possible to enter after first input.
This type of loops should be implemented by while loop .
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String yourdata=in.next();
if(yourdata.equals("end")){
//Stop the loop
}
//Do you code here
}

It bad practice because it's terminated only if next obtained token is "end". It does'n not consider situation like. e.g. end of input stream.
So when then stream ends and nowhere along "end" appeared you'l get s=null and NullPointerException at s.equals("end").
You can correct it e.g. by changing condition to in.hasNext() && !"end".equals(s).
Also s is never changing after it was initialized.

If the question is "why rewrite it" the answer is basically as others have pointed out, that it's currently an infinite loop, and also that it's not very readable as it stands. Personally I'd rewrite it as a while loop, which several others have already pointed out how to do, as it makes your intentions a little more clear than a for loop with a counter that's counting up to infinity. Someone unfamiliar with how the code is supposed to work could easily confuse an infinite increment to be an oversight by the programmer who wrote it.

The string s is never modified. The loop never ends. What about this :
Scanner in = new Scanner(System.in);
String s = "";
for (int i = 0 ; !s.equals("end"); i++) {
s = in.next();
System.out.println("The value of i is: " + i + " and you entered "
+ s);
}

Others have mentioned that the loop does not end because you are not changing the value of s, so the loop never ends. This may be what your professor intended, and it may not be. Bad code is bad practice, as a rule, but there are other reasons why this is bad practice.
What jumped out to me as being bad practice here, and what the professor could have intended, is the use of a for loop here. As my professor told me, "For loops are for when you know when you want the code to end, while loops are for when you don't know when you want the code to end." So if you have an iterable i such as this code:
for(i = 0; i<100; i++)
{
...
}
In this code, you know that you want to iterate i from 0 to 100. A while loop is what you would want to use in the situation your professor is discussing.
int counter;
while(*(str+counter))
counter++;
You have no idea when the loop is going to end, because you don't know how long the str is, but you know that sometime it will get to the null pointer, and the loop will terminate. This generally what is best practice.
So for the code your professor posted, you may want it to look like this:
Scanner in = new Scanner(System.in);
int i = 0;
while(!s.equals("end"))
{
i++;
String s = in.next();
System.out.println("The value of i is: " + i + " and you entered " + s);
}

It is not in good practice because of two things:
for loops are meant to iterate over a collection of data
a for loop consists of iterator initial state, loop condition and an iterating function that are related
The for statement just intermixes two different information (the stream and the counter). Even if it does work, it isn't good practice to do it.

I think this is bad practice, because there isn't any need for a for loop. In this case, I believe it's useless. It could be just this:
Scanner in = new Scanner(System.in);
String s = in.next();
if (!s.equals("end"))
{
System.out.println("You have enetered" + s);
}
See, there isn't any need for a loop. The loop you had was making things more complicated than they had to be. I was always think that things should be kept as simple as they can be unless they require complexity. For loops are only to be used when you have more than one action that you want the code to do. In the case above, only one thing is happening: the println statement, so there's no need for a loop. It's unnecesary...
Also, the loop never ends. So there's that too, but that's just faulty code. That's not why it's bad practice. It's bad practice because of the unnecesary use of a for loop. It's also faulty, because the code is wrong. So there are two different things going on with this code.

I would have just left a comment, but I don't have the rep yet.
What I haven't seen explained is WHY your s value is not changing.
In a typical for loop:
for(a=1; a<=10; a+=1) {body}
the initial phrase, 'a=1', is ONLY performed once as an initialization.
the third phrase, 'a+=1', is performed once at the end of every cycle, until…
the second phrase, 'a>=10', evaluates false.
so a for loop would be represented in 'psuedo-code' something like this:
a=1 // first phrase
:LoopLabel
{body}
a+=1 // third phrase
if (a<=10) // second phrase (boolean evaluation)
then goto LoopLabel
Likewise, your example, in similar pseudo-code might look like this:
Scanner in = new Scanner(System.in);
int i = 0;
String s = in.next()
:LoopLabel
{
System.out.println("The value of i is: " + i + " and you entered " + s);
}
++i
if (!s.equals("end"))
goto LoopLabel
So the reason your program was an infinite loop was the value of 's' was only set on entry to your loop and never changed during each loop execution, as most likely desired.

for (int i = 0; in.hasNext(); i++) {
String s = in.next();
if (s.equals("end")) {
break;
}
...
Endless loop, or no loop (when s is initially "end").

A number of responses above are correct to say that what you've written is an infinite loop. But I wanted to clarify why this is an infinite loop. The for loop you're using differs from the other form you may be thinking of:
String[] stringArray = { "1", "2", "3" };
for (String s : stringArray) {
System.out.println(s);
}
In that case, the variable s is initialized with the next value from your collection or array on each iteration. But that form of for loop works with collections and arrays and can't be used with iterators like the Scanner class.
The form of for loop you're using differs in that the initialization clause (where you have String s = in.next()) is called ONLY the first time through the loop. s is set that first time, then never changed.
You could re-write like this:
int i = 0;
for (String s = in.next(); !s.equals("end"); s = in.next()) {
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
But another bad thing in here is that there's no null or end check. It's conceivable if not likely that you would run out of strings before you found one that equaled "end". If that happened, then the for test clause (the middle one) would give you a NullPointerException when it tried to the call to the equals() method. THAT is definitely bad practice. I would probably re-write this like this:
int i = 0;
while (in.hasNext()) {
String s = in.next();
if (s.equals("end")) {
break;
}
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
If you really want a for loop instead of a while, it would be better to do this:
int i = 0;
for (Scanner in = new Scanner(System.in); in.hasNext();) {
String s = in.next();
if (s.equals("end")) {
break;
}
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
One last variation that preserves the test against the string in the test clause would look like this:
int i = 0;
String s = "";
for (Scanner in = new Scanner(System.in);
in.hasNext() && !s.equals("end");
s = in.next()) {
System.out.println("The value of i is: " + i++ + " and you entered " + s);
}
You could also add a null check in there before the s.equals("end") for total safety.

It is not a good practice maybe because you are comparing the String s with a String but you are not comparing the value, you are comparing the memory position of the s value.

Related

Setting up while and do-while loops from user input questions

I have to create a code used to determine the amount of insurance payout. I have to use a while loop after the initial prompt asking if they want to get an analysis. Then I need to use nested do-whiles, 2 do-while loops, in the prompts and if-else-ifs. I need help with the loops.
`
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String answer = " ";
String cont = ("%nMUTUALLY ACCIDENTAL, INC." +
"%n%nDo you want an analysis of earthquake coverage" +
"for your property? Enter 'Y' or 'N': ");
System.out.printf (cont);
(Scanner (answer = input.nextLine ()));
while (answer.equalsIgnoreCase ("Y"))
System.out.printf ("%nMUTUALLY ACCIDENTAL, INC." +
"%n%nEarthquake coverage analyzer" +
"%nPlease enter your name: ");
do
System.out.printf("%nPlease enter the insured value of your home: ");
System.out.printf("%nRichter Scale Damage Assessment"+
" 9.0+ Total destruction."+
" 8.0 Most structures dell."+
" 7.0 Many buildings destroyed"+
" 6.0 Many buildings considerably damaged, some collapsed."+
" 4.5 Damage to poorly constructed buildings."+
" 3.5 Felt by many people, no destruction."+
" 0 Generally not felt by people."+
"%n%nPlease enter the Richter scale value for the earthquake: ");
do
system.out.printf("%n“Your Name: “,Xxxxxxxxxx Xxxxxxxxxxxxxxx
“Home’s Insured Vale: “,$ZZZ,ZZZ,ZZZ9.99
“Richter Scale: “,Z9.99 or -Z9.99
“Is this information correct? ‘Y’ or ‘N’: “);
System.out.printf("%nDo you have another property? Enter 'Y' or 'N': ");
coverage = String.format(%n%nPAYOUT FOR EARTHQUAKE "+
"DAMAGE"+
"%N%NHOMEOWNER: %S"+
"$n$nDATE: %tD"+
"%nTime: %tr%n, insured, dateTime, dateTime);
coverage +=String.format("%n%-52s %4s $%,20.2f"+
"%nDeductible $47 $,20,2f"+
"%n46s TOTAL %4s $%,20.2f%n", message, " ", payout, " ", deductible, " ", " ", payout + deductible);
System.out.print(coverage) when richter > 0
exit main()
else
System.out.printf("%nThank you for using the Earthquake" +
"Coverage Analyzer.");
}
}
I can't see a clear question in here so I assume you are stuck on the structure of the loops.
while has the following structure:
// before
while (condition) {
statements;
statements;
}
//after
It first tests the condition. if true, it runs the statements. if the condition is false it skips straight to 'after'
do-while has the following structure:
// before
do {
statements;
statements;
} while (condition);
// after
It first runs the statements. then it tests the condition. if the condition is true it goes back into 'do' and runs the statements again. if the condition is false it goes to after.
You can nest loops like so:
while (someCondition) {
int i = 1;
String s = "";
// other code, just filling this to make it look a bit better
while (otherCondition) {
int j = i + 3; // i is available because this while is inside the block of the other while
}
}
You can do the same with do-while / mix them.
One additional thing: if you use break, you exit the loop you are in. if you have nested loops then you will break from the deepest loop.
while (someCondition) {
while (otherCondition) {
break; // goes to after-inner-while
}
// after-inner-while
}
sometimes you want to jump out of the outer while loop. break can help with this if you use labels. you can name loops like so:
outer: while (someCondition) {
inner: while (otherCondition) {
break outer; // goes to after-outer-while
}
// after-inner-while
}
// after-outer-while
this all also works for for-loops but you specifically asked questions about while loops.
be very careful about not using blocks after your while.
this is allowed but will be hard to read / a source of bugs:
while (someCondition)
doSomething();
it can easily be confuse you into thinking your code works differently than it actually does:
while (someCondition)
doSomething();
doAnotherThing();
the above only runs doSomething inside the loop but someone reading your code will likely think both method calls will be run.
Now to the code you posted:
I think you are expected to do something along the lines of:
boolean answeredYes = false;
while (!answeredYes) {
// ask for user input
// if user input is "Y" set answeredYes to true
}
since you say you need to use a while loop first. I would prefer do-while for this since you can do:
do {
// ask for user input
} while (userinput not what you expect);
My best advice right now is: don't try to write the entire method. Write code for one problem at a time. Start with the Y/N question and what you are supposed to do if the user types Y or N
then move on to the next step and work out what to do and how to do it. Write yourself comments (notes) that let you know what your intentions are.

Substring method to identify char value in string value

I'm having an issue with using the substring method to find a specific character in a string variable. Currently I have a for loop setup to loop over the length of a string variable named name. I then have my substring method inside of my if statement to find my specific character, in this case it is a ".".
I'm not able to get this to work and would appreciate any help. Thank you.
System.out.println("\nEnter name: ");
String name = in.nextLine();
int length = name.length();
for (int x = 0; x < length; x++) {
if(name.substring(x,x+1).equals(".")) {
System.out.println("Error! - name can not contain (.) values\n"
+ "***************************************************");
System.out.println("\nWould you like to capture another name?" +
"\nEnter (1) to continue or any other key to exit");
String opt1 = in.nextLine();
// If statement to run application from the start
if (opt1.equals("1")) {
System.out.println("menu launch");
}
else { System.exit(0); }
}
else { break; }
}
Don't reinvent the wheel. Instead of looping over the characters of the string, you could just use the contains method:
if (name.contains(".")) {
// logic comes here...
While Mureinik is correct on the best way to accomplish your goal, the reason your function does not work is because of your else { break; } statement.
break terminates the loop so unless the very first character is a ., then the loop will exit immediately after the first iteration. When you want to increment the loop, the correct keyword is continue although it is unnecessary in this case because all of the logic is housed inside of the if statement. Since there is no other logic to avoid, you should delete the else statement.

Using delimiters to split an equation and run it

So I am doing a project for a class of mine and it involves the use of delimiters and other scanner methods. However I've been doing a lot of research and the book we have does not clearly explain as to how it works. So after several headaches and trying to understand I figured I'd ask here (EDIT: This is something somewhat similar I found [relating to delimiters and splitting number sequences] to what my teacher was asking me and thought it would be adequate to ask it here. So before I get accused of doing my homework on here I wanted to clarify)
Here's what I have typed so far:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
/* sc.useDelimiter("\\s*"); With some help and research I found
out that the \\s* actually causes every character to be split
apart. so 33 is 3 3 */
int sum = sc.nextInt();
while(sc.hasNextInt( ))
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And my last attempt got me a weird output:
----jGRASP exec: java addUp
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 8
----jGRASP: operation complete.
Now I don't know a ton and I'm sure if I came in with something more complicated than the progress of what we've been through would not be appreciated (since I know I've seen some people answer other questions that is way over my understanding). So keep it dumbed down for me if you can XD. Thanks.
The problem with your code at the moment is that your while loop is checking for while(sc.hasNextInt( )), but it's expecting an operator. Change that to while(sc.hasNext() and you should be ok.
Additionally, when facing problems like this, try running your code in a debugger and stepping through it. You'd see pretty quickly that it didn't enter into the while loop and that would help you diagnose the problem. If you don't have access to a debugger, just put in some System.out.println() statements.
UPDATE
So, I ran your code in a debugger (after changing the while loop as I described), and the first thing I noticed was that the first call to sc.nextInt() returns 3, not 33, because of the reason H L explained. Having removed the call to setDelimeter, the code runs fine. It should now look like:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
//sc.useDelimiter("\\s*"); <-- don't do this
int sum = sc.nextInt();
while(sc.hasNext( )) // <-- not hasNextInt
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And outputs:
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 1249
Again, you should have spotted this if you stepped through your code in a debugger (Eclipse, IntelliJ, NetBeans, jdb, etc).
There are multiple issues with your code:
You call the next() and nextInt() methods multiple times within the while loop which consumes too much of our input.
The sum is initialized to 0 and the very first operand is omitted.
Only the last else block is executed because you compare strings with characters (single quotes instead of double quotes) which always evaluates to false.
Code:
// WRONG: sc.useDelimiter("\\s*");
int sum = sc.nextInt(); // consume the first token, must be an integer
while (sc.hasNext()) { // as long as there are more tokes, do the following
String operator = sc.next(); // read next token, must be a + or - sign
int operand = sc.nextInt(); // read next token, must be an integer again
// depending on the arithmetic operator we update the sum variable
if (operator.equals("-")) {
sum = sum - operand;
} else if (operator.equals("+")) {
sum = sum + operand;
} else {
// if the operator variable contains something else than a + or - sign
// we throw an exception. In general this is the preferred way to avoid
// that the software changes into an undefined state.
throw new RuntimeException("Unknown operator: " + operator);
}
}
System.out.println("Sum is: " + sum);
First Problem (Apparently corrected in an edit to the quesiton)
You call sc.next() in every if statement. Call it once, and then use the value when you need it. If you keep calling it, you'll keep eating your input!
String op = sc.next();
if (op.equals('-') {}
else if (op.equals('+') {}
else {}
Second Problem
You never initialize sum to the first number. You skip the first number completely! Start off like this to make sure you consume the first int before you consume the first operator.
int sum = sc.nextInt();
Third Problem
hasNextInt() only returns true if the next token is an int. It returns false if the next token is an operator like "+" or "-". Change your while to loop on hasNext().
The last fix may cause you to consume a "/n" or some other line seperator nonsense on your last iteration of the loop. as it stands, it looks like this will only cause you to print the sum twice. That seems like something you should be able to solve on your own.
Rather than making me edit my answer four MORE times, try to do this on paper, going in circles for the while loop. Consume an int. Consume an operator. Consume an int. Consume an operator. Consume an int. If you break that order, your logic isn't in the right order. Know the logic before you even try to write code.
Go read the Javadoc for Scanner to see what each method you are calling actually does. Learn about Streams in Java so you understand how they work.

Why doesn't my string change?

public static void read(String a[], double b[], String c) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
while (in.hasNext()) {
int i = 0;
String id = in.next();
String name = in.next();
String lastname = in.next();
double grade = in.nextDouble();
if (name.substring(0, 2).equalsIgnoreCase(c)) {
a[i] = id + "\t" + name + "\t" + lastname + "\t" + grade;
b[i] = grade;
}
i++;
}
}
When I use this method with
String men[] = new String[501];
double menGrade[] = new double[501];
read(men, menGrade, "MR");
My men[0] is assigned a String but men[1] to men [500] are all null ...
You need to declare your variable i outside of the while loop to keep it incremented.
Right now you are
declaring it with value 0
assign the values to the 1st array position
increment i, and then
declare it again with value 0 at the next loop iteration.
SO, just change your lines:
while (in.hasNext()) {
int i = 0;
to
int i = 0;
while (in.hasNext()) {
Your code has also other issues which you should adress in some way.
I do not know why you initialize your array with a fixed size of 500 and also check some conditions before you add your men and grades to those Arrays. This will however lead to a few problems if you are not careful.
Right now you would have holes in your array whenever the if condition does not evaluate to true.
Also your program would crash if there is more than 500 entries in your file.
A rather good solution when dealing with dynamic data structures (so, when you do not know beforehand how many records you will have exactly), is to use a dynamic data structure.
In java you can have a look at java.util.List interface and probably java.util.ArrayList as a good implementation.
Here is also the java doc of that class: Java Doc
Here you find more on the collections api which are a good thing for dynamic data structures: Collections - List tutorial
while (in.hasNext()) {
int i = 0;
...
This will RESET i each time you start the while loop and you always overwrite a[0] and b[0].
swap these two lines! (so the int i = 0; comes before the loop:
int i = 0;
while (in.hasNext()) {
...
You should increment i in your if statement and not always like you do now. You don't want holes in your men array.
This simply means, either your loop is executing only once.
Or, if block in loop is exceuting only once.
Dependecy is on the content of file you are importing and your if condition.
I'm pretty sure that something is wrong with your "data.txt" that caused the while loop to execute only once. Otherwise, I don't see any mistake in the code.
Why don't you check the value of i during the execution of the program?
If your data.txt file contains One single line then the corresponding while will be running for once populating the first element of the array i.e men in your case
The reason is this:
while (in.hasNext()) {
int i = 0;
...
i++;
}
you are destroying and creating i variable each time loop is executed effectively reseting it to 0 each time. Asides from notes from other answers you can simply move i outside the loop:
int i = 0;
while (in.hasNext()) {
...
i++;
}
Now I can't run in myself, but I see
while (in.hasNext()) {
int i = 0;
//other
a[i] = id + "\t" + name + "\t" + lastname + "\t" + grade;
b[i] = grade;
}
i++;
If you use a counter i over an array/Collection, generally you have to give a greater scope to counter.
if the counter is inside the while, at every iteration you recreate the counter and you point always at the same element of array
The/one solution can be:
int i=0;
while (in.hasNext()) {
//etc

Do-while loop won't escape - Java

Does a do-while loop check a value before or after it has been incremented? I can't seem to make this do-while loop escape, and can't determine if that is the mistake I am making. The point of this loop is to take input from the user and when they hit 'X', I want the loop to end. Am I using the wrong type of loop, or perhaps an incorrect statement?
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(coefficient[i] != "X");
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Specifically in your case, I'd change
} while(coefficient[i] != "X");
to something like:
} while(!"X".equalsIgnoreCase(coefficient[i]));
And you've got another problem in your code in that you want to test the user input which you place into coefficient[i], but then you promptly increment the i variable such that coefficient[i] no longer refers to the input.
So perhaps the test should instead be:
} while(!"X".equalsIgnoreCase(coefficient[i - 1]));
You're incrementing i between coefficient[i] = keyboard.nextLine(); and while(coefficient[i] != "X");, so in the while check coefficient[i] is null, also use .equals to compare strings.
int i = 0,
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];
do{
System.out.print("What is " + letter +"? ");
coefficient[i] = keyboard.nextLine();
i++;
letter++;
inputCount++;
}while(!coefficient[i-1].equals("X"));
There is two problems here. First you shouldn't compare Strings using logical operators. Use .equals instead.
For example:
coefficient[i].equals("X");
Secondly you are incrementing your array index counter before you check the while condition. So you actually need to subtract one from it to check if the most recently entered String was X.
See if using this will get it working:
coefficient[i-1].equals("X");

Categories