如何在Java中获取for循环的最后一个值? [英] How to take the last value of a for loop in Java?
问题描述
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中执行此程序.该程序将读取单词和字母,检查单词中是否包含字母.
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.
如果是,它将在单词中打印字母索引; 如果该字母出现多次,它将打印最后一个位置. 如果单词中没有字母,它将打印-1.
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.
当我在Codio中运行它时,有3个带有字母的位置:2、3和5.我只想取5.
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.
推荐答案
如果只想输出最后的发现,则需要移动
If you only want to output your last find, you need to move
System.out.print(match);
脱离循环.
但是在打印match
之前,请确保计数器为>0
.否则,您会得到0-1
作为输出.
But make sure that your counter is >0
before you print match
. Else you would get 0-1
as an output.
要执行此操作,请添加另一个if (counter > 0) { }
或将打印内容移至您现有的if (counter == 0)
To do this either add another if (counter > 0) { }
or move the print into the else block of your already existing if (counter == 0)
这篇关于如何在Java中获取for循环的最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!