-4

The String asd prints double before asking the input for switcher, I feel hopeless now. I want the string "asd"to only print once but in my case in prints twice, my guess would be an error or looping, sorry I'm very new here and into programming

public class FruitBasket {

static String option;
static String choice1;
static int catcher;
static int counter1 = 1;
static int counter = 0;
static String eater = "e";
static Scanner sc = new Scanner(System.in);       
static Stack<String> basket = new Stack();
static String switcher;

public static void main(String[] args) {

    catching();

}

static void catching(){

    System.out.println("Catch and eat any of these fruits: " + "'apple', 'orange', 'mango', 'guava'" );
    System.out.println("A apple, O orange, M mango, G guava");
    System.out.print("How many fruits would you like to catch? ");
    catcher = sc.nextInt();

    switches();
     }

     static void switches(){

    while(counter1 < catcher)  {
    String asd = "Fruit " + counter1 + " of " + catcher + ":";
    System.out.print(asd);

    switcher = sc.nextLine();
         switch (switcher) {
            case "a":
                basket.push("apple");
                counter++;
                counter1++;
                break;
cedieasd
  • 3
  • 2
  • You aren't showing us how you initialize counter and catcher, I tried with catcher = 4 and counter = 0 and the string asd doesn't print twice. – emankcin Sep 09 '19 at 15:12
  • pardon I'm so noob. the int counter is just "static int counter;" for the catcher would be "System.out.print("How many fruits would you like to catch? "); catcher = sc.nextInt();"" – cedieasd Sep 09 '19 at 15:19
  • 1
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Tom Sep 09 '19 at 15:21
  • Java and JavaScript are completely unrelated languages. – EJoshuaS - Reinstate Monica Sep 09 '19 at 15:24

1 Answers1

0

It's because you are using sc.nextInt() to get input from the user and it doesn't consume the line so when you use switcher = sc.nextLine(); it still reads the number that the user entered before.

You can add this after catcher = sc.nextInt(); to consume the line:

    if (sc.hasNextLine()){
        sc.nextLine();
    }

Or alternatively you could use:

catcher = Integer.parseInt(sc.nextLine());

To convert the user input to an integer value and it will also work.

emankcin
  • 76
  • 3