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

Check if user entered both a first and last name

我正在制作一个程序,为输入的姓名提供随机彩票号码。但问题是我必须确保用户输入了名字和姓氏。我正在使用一种方法在用户输入中找到 space,然后从该数据创建子字符串,但我一直在我的 for 循环下收到错误 "incompatible type"。任何帮助将不胜感激!

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();
    }       
  }
}

indexOf() 将 char 作为输入(在您的情况下)。将 i 更改为 " "(space)

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

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

然后你创建一个方法 return 如果用户输入全名则为真。

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

你需要这样写

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

但是为什么选择for循环?

@sweeper 给出了最佳方案