检查用户是否同时输入了姓氏和名字

时间:2015-09-25 05:20:07

标签: java string int indexof

我正在制作一个程序,为输入的名字提供随机抽奖号码。但问题是我必须确保用户同时输入名字和姓氏。我正在使用一种方法在用户输入中找到空格,然后从该数据创建子串,但我继续在我的for循环下获得错误“不兼容类型”。任何帮助将不胜感激!

enter code here
import java.util.Scanner;      //Import scanner class
import java.util.Random;       //Import random number generator
import java.io.*;              //Import PrintWriter

public class Lab4ZinkovskyFl   //Program that lets user enter a name and generates random lottery numbers for that name
{
public static void main (String[] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);

Random randomNumbers = new Random();

String again = "y";                      //Control the loop
int r1 = randomNumbers.nextInt(100)+ 1;  //*******************
int r2 = randomNumbers.nextInt(100)+ 1;  //*   Random lottery  
int r3 = randomNumbers.nextInt(100)+ 1;  //*   numbers for    
int r4 = randomNumbers.nextInt(100)+ 1;  //*   program        
int r5 = randomNumbers.nextInt(100)+ 1;  //******************* 

    while (again.equalsIgnoreCase ("y"))  // Allows the user to continue the loop
    {
        System.out.println ("Please enter first and last name to enter the lottery.");
        String fullName = keyboard.nextLine();

        boolean space = false;  // Checks for first and last name       

        for (int i = 0; i < fullName.length(); i++)
        {       
            if (fullName.indexOf(i) == " ")
            {
                space = true;
                spaceIndex = i;
            }
            else 
            {
                System.out.println ("Error, please enter both first and last name to continue.");
            }

        }
    String firstName = fullName.substring (0, spaceIndex);
    String lastName = fullName.substring (spaceIndex, fullName.length());

    System.out.println (lastName + ", " + firstName + ": " + r1 + ", " + r2 + ", " + r3 + ", " + r4 + ", " + r5);


    System.out.println ("Run the lottery again? (y=yes)");
    again = keyboard.nextLine();
    }       
  }
}

3 个答案:

答案 0 :(得分:2)

您可以将用户输入拆分为“”,如下所示:

String[] names = fullName.split(" ");

然后,如果用户输入全名,则创建一个返回true的方法。

for (int i = 0 ; i < names.length ; i++) {
    if (names[i].trim().equals("")) {
        names[i] = null;
    }
}
int elementsWithText = 0;
for (int i = 0 ; i < names.length ; i++) {
    if (names[i] != null) {
        elementsWithText++;
    }
}

return elementsWithText == 2;

这样的事情。希望你能算出我在做什么。如果您不知道方法调用正在做什么,它们都来自String。这是文档:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

答案 1 :(得分:0)

indexOf()接受一个char作为输入(在你的情况下)。将我改为&#34; &#34;(空格)

答案 2 :(得分:0)

你需要这样写

  if (fullName.indexOf(" ") == -1) 
   {
     System.out.println ("Error, please enter both first and last name to continue.");
   }
   else 
   {
     space = true;
     spaceIndex = i;
   }

但为什么选择循环?

@sweeper提供了最佳解决方案。