-1

I want to end whileloop, regardless of the length. For python a (-1) is returned when the index exceeds the length of the string. But I can't find to work out how to do the same in java.

 while(true) {
        System.out.println("Letter nur " + (i+1) + " is " + name.charAt(i));
        if(name.charAt(i)==-1){
            break
        }
        i = i + 1;

Can I and if yes, how?

4
  • 5
    When iterating over a sequence of fixed length, use a for loop instead of a while loop. This is true for both Python and Java. Commented Jan 16, 2018 at 20:52
  • 1
    I don't see how you could get a -1 in Python. There is no charAt method on string, and indexing past the end would raise an exception. Commented Jan 16, 2018 at 20:55
  • @FredLarson Perhaps the OP is confused with slicing syntax where you can use -1 as an index? Commented Jan 16, 2018 at 20:57
  • @Code-Apprentice: Maybe, but that doesn't seem to relate well to this question. Commented Jan 16, 2018 at 20:58

2 Answers 2

2

Use a for loop:

for (int i = 0; i < name.length(); i++) {
    System.out.println("Letter nur " + (i+1) + " is " + name.charAt(i));
}
Sign up to request clarification or add additional context in comments.

7 Comments

Can you do for (char c : s) in Java? It has been too long since I wrote any Java code.
@Code-Apprentice You can do for (char c : s.toCharArray()). But then you can't print i+1.
You could also just put the test part of this if in the while. But I think range-for is the best idea.
Thanks! I'm doing an exercise where I'm suppose to compare the time for while and for loops. But if i were to compare while(i < name.length() and for(int i = 0; i < name.length(); i++) wouldnt that be almost the same thing?
@parvelmarv Yes. The for loop is just more conventional.
|
0

You can easily use length() function for this purpose. But according to question, you want to end while loop at the end of string. This can be done as follows:

    int i=0;
    while(true){
        try{
            System.out.print(""+as.charAt(i));
            i++;
        }
        catch(java.lang.StringIndexOutOfBoundsException e){
            break;
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.