gpt4 book ai didi

java - 无法实现内部 "for"循环

转载 作者:行者123 更新时间:2023-12-01 19:02:22 24 4
gpt4 key购买 nike

Java 代码:

public class PrintDuplicates {

Scanner sc = new Scanner(System.in);
String ch;

public void getUserInput() {
System.out.print("Enter the string or number: "+System.lineSeparator());
ch = sc.next();
}

public void findDuplicates() {
for(int x=0; x<ch.length(); x++) {
for(int y=x+1; y<ch.length(); y++) {
if(ch.charAt(x)==ch.charAt(y)) {
System.out.println("Duplicates: "+ch.charAt(x));
}
}
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
PrintDuplicates obj = new PrintDuplicates();
obj.getUserInput();
obj.findDuplicates();
}

}

Python 代码:

ch = None

def getUserInput():
global ch
ch = input("Enter the string OR number: ")

def findDuplicates():
for x in ch:
###NEED HELP with the following part of Python code (next 3 lines)
for ____ in ch:
if(_____):
print("Duplicate: %d" %x)
getUserInput()
findDuplicates()

问题陈述:基本上,我希望找到字符串中的重复项并将其打印在屏幕上(注意:作为引用,我已经在 java 中创建了等效/预期的代码)

最佳答案

尝试下面的代码

ch = None

def getUserInput():
global ch
ch = input("Enter the string OR number: ")

def findDuplicates():
for x in range(len(ch)):
for y in range(x+1, len(ch)):
if(ch[x]==ch[y]):
print("Duplicate: %s" %ch[x])
getUserInput()
findDuplicates()

如有必要,您可以避免多个 for 循环,

def findDuplicates():
for x in (i for i in set(s) if s.count(i)>1):
print("Duplicate: %s" % x)

关于java - 无法实现内部 "for"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59616160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com