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.
I'm looking for help with a question I have. We just started learning simple java in our course after learning a tonne of C++.
One of our bonus missions for people who know code more than what was taught in class.
The mission is as follows: Write a function by the name lettersSeries which gets letters (one letter at a time, assume all letters are lower case) inputted from the user. The function stops accepting letters from the user once the user has inputted 3 consecutive letters. (Only for loops can be used without while loops)
Example: a -> b -> a -> c -> d -> e (Here is stops)
As far I don't know much and I would be happy if someone would help me with this... I tried some options but I have no idea how to trace the alphabet, and especially how to check if letters are consecutive...
Thanks!
public static void letterSeries() {
//We create a scanner for the input
Scanner letters = new Scanner(System.in);
for(Here I need the for loop to continue the letters input) {
//Here I need to know if to use a String or a Char...
String/Char letter = next.<//Char or String>();
if(Here should be the if statement to check if letters are consecutive) {
/*
Here should be
the rest of the code
I need help with
*/
Obviously, you could change the code, and not make my pattern, I would just be happier with an easier way!
Here's how I would tackle the problem, I'm going to let you fill in the blanks with this though so I don't do all of your homework for you.
private void letterSeries() {
Scanner scanner = new Scanner(System.in);
char prevChar;
char currChar;
int amountOfConsecutives = 0;
final int AMOUNT_OF_CONSECUTIVES = 2;
for(;;) {
// Take in the users input and store it in currChar
// Check if (prev + 1) == currChar
// If true, amountOfConsecutives++
// If false, amountOfConsecutives = 0;
// If amountOfConsecutives == AMOUNT_OF_CONSECUTIVES
// Break out of the loop
}
}
You can use chars' Unicode number to check if letters are consecutive: if a and b are your letters, try to check if b - a == 1. If consequentiality is intended in a case-insensitive way ('B' consecutive to 'a') then check: (b - a == 1 || b - a == 33).
Scanner letters = new Scanner(System.in);
char previousChar = '\0';
int consecutive = 1;
for(; consecutive != 3 ;){
char userInput= letters.findWithinHorizon(".", 0).charAt(0);
if (userInput - previousChar == 1){
consecutive++;
} else {
consecutive = 1;
}
previousChar = userInput;
}
I cheated a little bit with this solution. I used a for loop with only the middle part so it acts like a while loop.
Anyway, here's how it works.
The first three lines create a scanner for user input, a consecutive variable that counts how many consecutive letters the user enters, and a previousChar to store the previous character.
"Why does consecutive start at 1?" you might ask. Well if the user enters one letter, it is going to be consecutive with itself.
In the for loop, as long as consecutive != 3, the code is going to run. The first line in the loop we read a character using findWithinHorizon(".", 0).charAt(0). And then the if statement checks whether it is a consecutive letter with the previous character. If it is, add one to consecutive and if not, reset consecutive to one. Lastly, we set previousChar to userInput to prepare for the next iteration.
private void letterSeries() {
Scanner letters = new Scanner(System.in);
String last = "";
int counter = 0;
for (;counter < 2;){
if ( last.equals (last=letters.next())) counter ++;
else counter = 0
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.
You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)
You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).
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.
I am making an inefficient calculator type of program that takes values from user defined arrays and plugs them into an equation that the user also defines. To do this I needed to make my program change my string to a char array, the problem? I have it so that users must use A1-10 to reference the definded index and I cannot find a way to make the program search the next array for the number to specify what array the program is accessing.
out.println("Please input a string of commands in a format similar to this: ");
out.println("([A1]-[A2]=) or ([A8]+[A6]=) or ([A1]-[A4]+[A7]*[A10]/[A3]=)");
out.println("Use only the numbers 1-10 when referencing an array. \n You may always type in 'Help' if you need help. ");
String eString = scn.nextLine();
if ("help".equals(eString)) {
out.println("Figure it our yourself...");
} else {
for (char c: eString.toCharArray()) {
if (c == 'A') {
}
}
the code got a little jumbled up while changing code and I haven't taken the time to make it look nice and pearly again.
If you need the index you should just use a normal for loop instead of an enhanced for loop.
char[] input = eString.toCharArray();
for(int i = 0; i < input.length; i++) {
if(input[i] == 'A'){
// You know the index of A here.
}
}
You should also use "help".equalsIgnoreCase(eString) when comparing with help so that they can enter either "Help" or "help" (link to doc)