-2

So after I input the numbers needed for the while instruction, it should display the result and then the "Enter your name here:" text. Afterwards I should be able to input text, but apperantly I can't, it just displays the "Hello" message and jumps to the next instruction.

However, if I write the text right after the series of numbers, it works just fine. How can I make the program let me input text after the "Enter your name here" message?

import java.util.Scanner;

public class apples {
    public static void main(String[] args) {
        Scanner cristi = new Scanner(System.in);

        int age= 21, k=10, nr=1, sum=0, val=0;
        k=cristi.nextInt();
        while(nr<=k){
            val=cristi.nextInt();
            sum=sum+val;
            nr++;
        }
        sum=sum/k;
        System.out.println(sum);

        System.out.println(age>50 ? "You are old!" : "You are young!");

        tuna tunaObject= new tuna();
        System.out.println("Enter the name here: ");

        String a= cristi.nextLine();
        tunaObject.simpleMessage(a);

        System.out.println("Enter first name: ");
        String temp= cristi.nextLine();

        tunaObject.setName(temp);
        tunaObject.afisaj();         
    }
}
khelwood
  • 46,621
  • 12
  • 59
  • 83
John Doe
  • 11
  • 7
  • 2
    Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – khelwood Aug 01 '17 at 09:20

2 Answers2

1

This is an issue about buffers and Scanner. To resolve your issue, just do cristi.nextLine() after each cristi.nextInt()so you clear the buffer.

For more info, you can look at this thread

Xatyrian
  • 1,324
  • 5
  • 25
  • Got it now. Thanks. I am in my first week of studying Java and I got used to C++, which didn't have such issues. – John Doe Aug 01 '17 at 10:37
0

Add the line:

cristi.nextLine();

after the while loop to solve your problem.

Edit: @Xatyrian answer provides more context.

Ekaba Bisong
  • 2,555
  • 2
  • 19
  • 34