-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?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
parvelmarv
  • 11
  • 1
  • 4

2 Answers2

2

Use a for loop:

for (int i = 0; i < name.length(); i++) {
    System.out.println("Letter nur " + (i+1) + " is " + name.charAt(i));
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Can you do `for (char c : s)` in Java? It has been too long since I wrote any Java code. – Code-Apprentice Jan 16 '18 at 20:55
  • @Code-Apprentice You can do `for (char c : s.toCharArray())`. But then you can't print `i+1`. – shmosel Jan 16 '18 at 20:57
  • You could also just put the test part of this `if` in the `while`. But I think range-for is the best idea. – Fred Larson Jan 16 '18 at 21:00
  • 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 Jan 16 '18 at 21:02
  • @parvelmarv Yes. The `for` loop is just more conventional. – shmosel Jan 16 '18 at 21:05
  • @parvelmarv: Perhaps that's one point of the exercise -- to see the relationship between `while` and `for`. Also, see https://stackoverflow.com/q/1165457/10077 – Fred Larson Jan 16 '18 at 21:06
  • Since you are comparing the timing of for vs while, you should still keep the logic as close as possible. This means using `while(i < name.length())` rather than an `if` statement with a break. Of course, you could compare all three of these options to see if there is any difference in the timing. – Code-Apprentice Jan 16 '18 at 22:33
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;
        }
    }
ASG
  • 1