user3015645
user3015645

Reputation: 31

Rotating words in a string in java

The program is supposed to take a sentence inputted by the user such as "I am very hungry" and then ask a number of words to rotate. If the number was 2 the new output would be "very hungry I am". This is my code so far but I seem to have an error. When I run the code, this appears: java.util.InputMismatchException. There is also some other information that appears under it but I am not sure what it means. This is my code so far.

import java.util.*;
public class WordRotation
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a sentence");

     if(input.hasNext());
    {
      String s = input.next();

      String[] words = s.split(" ");

      System.out.println("Enter number of words to be rotated");
      int rotation = input.nextInt();

      for (int i = 0;i < words.length;i++)
      {
        System.out.print(words[(i + words.length - rotation)%words.length] + " ");
      }
    }
  }
}

I tried to change my if statement to a while statement but the code never outputs anything, it just keeps loading.

Upvotes: 0

Views: 3891

Answers (2)

mdolbin
mdolbin

Reputation: 936

Change String s = input.next(); to String s = input.nextLine();


Yeah, it is actually a solution because after we hit enter, there is a \n still left in stream after we hit Enter and .nextInt() reads that \n and your number. If we use input.nextLine() instead of input.next() we will capture that \n and input.nextInt() will read next integer without \n.

There is more info https://stackoverflow.com/a/7056782/1366360

Upvotes: 2

constantlearner
constantlearner

Reputation: 5247

You need to read again from input after your

  System.out.println("Enter number of words to be rotated");

add this line

Scanner input2 = new Scanner(System.in);
  int rotation = input2.nextInt();

Upvotes: 0

Related Questions