How to take the last value of a for loop in Java?

风流意气都作罢 提交于 2021-01-28 02:36:43

问题


import java.util.Scanner;
public class Problem1{
  public static void main(String[] args){
    //input
    Scanner kb = new Scanner(System.in);
    String word,letter;
    int counter=0, match,value;
    word=kb.next();
    word=word.toLowerCase();
    letter=kb.next();
    letter=letter.toLowerCase();
    //loop
    for (int i=0;i<word.length();i++)
      if (word.charAt(i)==letter.charAt(0)){
        counter++;
        match=i;
    System.out.print(match);
    }
    if (counter==0)
      System.out.print(-1);
  }
}

I must execute this program in Codio. This program will read a word and a letter, check whether the letter is in the word or not.

If yes, it will print the letter's index in the word; If the letter occurs more than once, it will print the last location. If the letter is not in the word, it will print -1.

When I ran it in Codio, there were 3 locations that had the letter: 2, 3 and 5. I only want to take 5.

I would be really grateful if anyone could help me with this.


回答1:


If you only want to output your last find, you need to move

System.out.print(match);

out of the loop.

But make sure that your counter is >0 before you print match. Else you would get 0-1 as an output.

To do this either add another if (counter > 0) { } or move the print into the else block of your already existing if (counter == 0)



来源:https://stackoverflow.com/questions/52529746/how-to-take-the-last-value-of-a-for-loop-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!