我刚开始写java并且有一个问题我必须完成大学学业。 到目前为止,我已经完成了问题要求我做的所有事情,除了我必须输入名称的最后一部分,如果名称与字符串数组中的名称相匹配,它将计算值。现在卡住它2小时,请帮忙
System.out.println();
System.out.print("Enter the candidate's name: ");
candi[0] = keyIn.nextLine();
for(int i = 0; i<votes.length; i++)
{
if(candi[0].equals(names[i]))
{
for(int h = 0; h<votes.length; h++)
{
if(votes[i] == votes[h])
{
same = same+1;
}
else if(votes[i]<votes[h])
{
less = less+1;
}
else if(votes[i]>votes[h])
{
more = more + 1;
}
}
}
else
{
System.out.print("Name does not match, enter again : ");
candi[0] = keyIn.nextLine();
}
}
答案 0 :(得分:0)
您的问题是您只检查每个输入的一个名称(i
处的名称)。您需要遍历所有名称以检查输入的名称是否与数组中的一个匹配。为了解决这个问题,我将整个事情包装在一个while
循环中,并将匹配检查分离到它自己的小for
循环:
String[] names = {"Dunne","Doherty","McGlynn","Grant","Sweeney","McHugh","Gibbons","O'Neill"};
int[] votes = {0,13,28,6,6,29,15,5};
double[] avg = {0.0,12.7,27.5,5.9,5.9,28.4,14.7,4.9};
System.out.println();
System.out.print("Enter the candidate's name: ");
Scanner scan = new Scanner(System.in);
String in = scan.nextLine();
boolean containsName = false;
while (true) { // continue asking for names until one mathces
// Check if name is present
for(int i = 0; i<names.length; i++)
{
if(in.equals(names[i]))
{
containsName = true;
break; // break the for loop
}
}
// do something if name is present, continue if not
if(containsName) {
System.out.println("Calc!");
break; // break the while loop
}else {
System.out.print("Name does not match, enter again : ");
in= scan.nextLine();
}
}
答案 1 :(得分:0)
我猜您正在寻找类似的内容:
您可以在找到用户输入的名称时执行某些操作 在候选人名单中。
工作代码:
import java.util.Scanner;
class match {
match() {
Scanner keyIn = new Scanner(System.in); //for taking input
String candi[] = new String[1]; //for storing name input
String candiNames[] = { "ab", "bc", "cd" }; //String array of candidate names
Boolean found = false; //flag to check if name found or not
System.out.print("Enter the candidate's name: ");
candi[0] = keyIn.nextLine(); //taking input
for (String n : candiNames) { //looping
if (candi[0].equalsIgnoreCase(n)) { //matching string (ignoreing case)
found = true;
// do the working here for anything you wish to do on match
// found
}
}
if (found == true) {
System.out.println("Match found ");
} else if (found == false) {
System.out.println("Match not found for : " + candi[0]);
}
}
}
public class StringName {
public static void main(String args[]) {
new match();
}
}
输出:
我希望我帮助过。)