简体   繁体   English

Java:如何确保或使用户输入字符串中的逗号?

[英]Java: How do I ensure, or make a user, input a comma in a string?

First off, I am brand new to both Java and to this website. 首先,我对Java和此网站都是全新的。 I am going to ask my question as thoroughly as I can. 我将尽可能详尽地问我的问题。 However, please let me know if you think I left something out. 但是,如果您认为我遗漏了一些东西,请告诉我。

I am working on a school assignment, and I am stuck on the second portion of it. 我正在做一项学校作业,而我却停留在第二部分。 I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. 我能够提示用户,但对于我自己却一生无法解决,请弄清楚如何确保输入字符串包含逗号。 I did try searching this site, as well as Googling it, and haven't been able to find anything. 我确实尝试搜索该网站以及对其进行谷歌搜索,但是却找不到任何东西。 Perhaps I am not wording the question appropriately. 也许我没有适当地措辞这个问题。

(1) Prompt the user for a string that contains two strings separated by a comma. (1)提示用户输入包含以逗号分隔的两个字符串的字符串。 (2) Report an error if the input string does not contain a comma. (2)如果输入字符串不包含逗号,则报告错误。 Continue to prompt until a valid string is entered. 继续提示直到输入有效的字符串。 Note: If the input contains a comma, then assume that the input also contains two strings. 注意:如果输入包含逗号,则假定输入也包含两个字符串。

So far I have this: 到目前为止,我有这个:

public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in); // Input stream for standard input
    Scanner inSS = null;                   // Input string stream
    String lineString = "";                // Holds line of text
    String firstWord = "";                 // First name
    String secondWord = "";                  // Last name
    boolean inputDone = false;             // Flag to indicate next iteration

    // Prompt user for input
    System.out.println("Enter string seperated by a comma: ");

    // Grab data as long as "Exit" is not entered
    while (!inputDone) {

        // Entire line into lineString
        lineString = scnr.nextLine();

        // Create new input string stream
        inSS = new Scanner(lineString);

        // Now process the line
        firstWord = inSS.next();

        // Output parsed values
        if (firstWord.equals("q")) {
            System.out.println("Exiting.");

            inputDone = true;

        if else (lineString != ",") {     // This is where I am stuck!
            System.out.print("No comma in string");
        }
        } else {
            secondWord = inSS.next();


            System.out.println("First word: " + firstWord);
            System.out.println("Second word: " + secondWord);

            System.out.println();
        }
    }

    return;
}

} }

I know my "if else" is probably not correct. 我知道我的“否则”可能是不正确的。 I just don't know where to begin for this particular command. 我只是不知道从哪个特定命令开始。 Unfortunately my eBook chapter did not cover this specifically. 不幸的是,我的电子书一章没有专门介绍这一点。 Any thoughts would be greatly appreciated. 任何想法将不胜感激。 Thank you so much! 非常感谢!

I suspect you want to assert if the input contains a comma, and at least one letter either side . 我怀疑您想断言输入中是否包含逗号, 并且两侧至少包含一个字母 For this you need regex: 为此,您需要正则表达式:

if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
    System.out.print("Input not two comma separated words");
}

Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(',') is what you want. 由于您要查找包含逗号的字符串,并且想要获取逗号前的字符串和逗号后的字符串,因此需要使用string.split(',')。 Asking if the string “Contains” a comma gives you no information about the string before or after the comma. 询问字符串“包含”逗号是否会为您提供有关逗号之前或之后的字符串的任何信息。 That's where string.split() helps. 这就是string.split()帮助的地方。 Since you don't care “Where” the comma is you simply want the string before the comma and the string after the comma. 由于您不在乎“哪里”,因此您只需要逗号前面的字符串和逗号后面的字符串。 The string.split(',') method will return a string array containing the strings that are separated by commas (in your case) or any character. string.split(',')方法将返回一个字符串数组,其中包含用逗号(对于您而言)或任何字符分隔的字符串。 Example: 例:

string myString = “firstpart,secondpart”;

… then … 然后

string[] splitStringArray = myString.Split(‘,’)

This will return a string array of size 2 where 这将返回一个大小为2的字符串数组,其中

splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"

with this info you can also tell if the user entered the proper input… ie… 通过此信息,您还可以判断用户是否输入了正确的输入…即…

if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. 如果splitStringArray.Length(或Size)= 0,则用户未输入任何内容;如果splitStringArray.Length(或Size)= 1,则用户输入1个不带逗号的字符串…可能会在此处检查退出。 If the splitStringArray.Length (or Size) = 2 then the user input the string properly. 如果splitStringArray.Length(或Size)= 2,则用户正确输入了字符串。 if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma. 如果splitStringArray.Length(Size)> 2,则用户输入的字符串超过1个逗号。

I hope that helps in describing how string.split works. 我希望这有助于描述string.split的工作方式。

Your code however needs some work… without going into much detail below is ac# console while loop as an example: 但是,您的代码需要做些工作……下面以ac#控制台的while循环为例:

inputDone  =  false;
while (!inputDone)
{
  Console.Clear();
  Console.WriteLine("Enter string seperated by a comma: ");
  lineString = Console.ReadLine();
  string[] splitStringArray = lineString.Split(',');

  // check for user to quit
  if (splitStringArray.Length == 1)
  {
    if (splitStringArray[0] == "q")
    {
      inputDone = true;
      Console.Clear();
    }
    else
    {
       // 1 string that is not "q" with no commas
    }
  }

  if (splitStringArray.Length == 2)
  {
    // then there are exactly two strings with a comma seperating them
    // or you may have ",string" or "string,"
    Console.WriteLine("First word: " + splitStringArray[0]);
    Console.WriteLine("Second word: " + splitStringArray[1]);
    Console.ReadKey();
  }
  else
  {
    Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
    Console.ReadKey();
  }

}   

Hope that helps. 希望能有所帮助。

This worked for me: 这为我工作:

import java.util.Scanner;
import java.io.IOException;

public class ParseStrings {

    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        Scanner inSS = null;
        String lineString = "";
        String firstWord = "";
        String nextWord = "";

        System.out.println("Enter input string: ");

        while (lineString.matches("q") == false) {
            lineString = scnr.nextLine();
            lineString = lineString.replaceAll(",",", ");
            inSS = new Scanner(lineString);
            int delimComma = lineString.indexOf(",");

            if ((delimComma <= -1) && (lineString.matches("q") == false)) {
                System.out.println("Error: No comma in string");
                System.out.println("Enter input string: ");
            }

            else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
                System.out.println("Error: Two words");
                System.out.println("Enter input string: ");
            }

            else if (lineString.matches("q") == false) {
                firstWord = inSS.next();
                nextWord = inSS.nextLine();
                System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));

                System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));

                System.out.println("\n");

                System.out.println("Enter input string: ");
            }
            continue;
        }

        return;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM