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);
}
}
我必须在 Codio 中执行这个程序。该程序将读取一个单词和一个字母,检查该字母是否在单词中。
如果是,则会打印该字母在单词中的索引; 如果该字母出现多次,它将打印最后一个位置。 如果该字母不在单词中,则会打印-1。
当我在 Codio 中运行它时,有 3 个位置有字母:2、3 和 5。我只想取 5。
如果有人能帮助我,我将非常感激。
最佳答案
如果你只想输出你最后的发现,你需要移动
System.out.print(match);
跳出循环。
但在打印 match
之前,请确保您的计数器为 >0
。否则,您将得到 0-1
作为输出。
为此,可以添加另一个 if (counter > 0) { }
或将打印内容移至现有 if (counter == 0)
的 else block 中
关于java - Java中如何获取for循环的最后一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529746/