简体   繁体   中英

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of 'apple' is 2".

What I did so far does not work. Is it my way of storing the input into the string array not correct?

import java.util.Scanner;

public class test {
    public static void main(String [] args) {

        System.out.println("Enter sentence: ");

        Scanner sc = new Scanner(System.in);

        String input = sc.nextLine();

        int num=1;
        String sentence[]=new String[num];

        for(int i=0; i< num; i++) {

          sentence[i] = input; // store the user input into the array.
          num = num+1;
        }


        System.out.println("Enter the given words to find the index of its first match: ");
        Scanner sc2 = new Scanner(System.in);
        String key = sc2.next(); 

        for(int j=0; j<num; j++) {
            while (sentence[j].equals(key)) {
                System.out.println("The index of the first match of "+key+" is "+j);
            }
        }
    }   
}

String array is not required in your solution.

Try this :-

    System.out.println("enter sentence ");
    Scanner sc = new Scanner(System.in);

    String input = sc.nextLine();

    System.out.println("enter the given word to fin the index ");

    sc = new Scanner(System.in);

    String toBeMatched = sc.nextLine();

    if (input.contains(toBeMatched)) {
        System.out.println("index is  " + input.indexOf(toBeMatched));
    } else {
        System.out.println("doesn't contain string");
    }
  • sentence variable is only defined inside the for loop, it needs to be declared outside it
  • You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
  • sentence[i] = input -- will mean -- sentence[0] = "I love apple"
  • Scanner variable can do all the work for you for the input into the array instead of a for loop

String[] a = sc. nextLine(). split(" ");

This will scan an input of new line and separate each string separated by a space into each array.

System.out.println("Enter sentence: ");

Scanner sc = new Scanner(System.in);

String[] sentence = sc. nextLine(). split(" ");

System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine(); 

for(int j=0; j<num; j++) {
    if (sentence[j].matches(key)) {
        System.out.println("The index of the first match of "+ key +" is "+ j);
    }
}
  • Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
  • The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.

  • Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List .

     public static void main(String[] args) throws IOException { System.out.println("Enter sentence: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); System.out.println("Enter the given word to find the index of its first match: "); Scanner wordInput = new Scanner(System.in); String key = wordInput.next(); String[] words = input.split(" "); int occurence = Arrays.asList(words).indexOf(key); if(occurence != -1){ System.out.println(String.format("Index of first occurence of the word is %d", occurence)); } } 

You just need to declare sentence array outside the for loop, as for now, the issue is of scope. For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.

So, the input which you will get will come in String[] args. For more on command line arguments check here .

I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.

I also noticed a couple of errors. You could try this

public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Enter Sentence");
    Scanner sc = new Scanner(System.in);

    String input = sc.nextLine();
    String sentence[] = input.split("\\s");


    System.out.println("Enter Word");
    Scanner sc2 = new Scanner(System.in);
    String key = sc2.next();

    int index = 0;
    for(String word : sentence)
    {

        if(word.equals(key))
        {
            System.out.println("The index of the first match of " + key + " is " + index);
            break;
        }
        index++;
    }

}

Turtle

I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.

public class ConfigTest {

   public static void main(String[] args) {

      System.out.println("Enter sentence: ");
      Scanner sc = new Scanner(System.in);

      String input = sc.nextLine();
      // Use this to split the input into different indexes of the array
      String[] sentence = input.split(" ");

      System.out.println("Enter the given words to find the index of its first match: ");
      Scanner sc2 = new Scanner(System.in);
      String key = sc2.next();

      for (int i = 0; i < sentence.length; i++) {
         if (sentence[i].equals(key)) {
            System.out.println("The index of the first match of " + key + " is " + i);
         }
      }

   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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