3

The Programm is supposed to let me enter a value a and a string. While it lets me input he integer when it comes to the string, it prints the question but does not let me enter anything.

import java.util.Scanner;

public class PrSumN {
  public static void main(String args[]) {
    System.out.println("Enter a value");
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int sum = 0;
    int pr = 1;
    System.out.println("Do you want the sum of the numbers or the products of the numbers?");
    String answer = sc.nextLine();
    //Itdoesnotletmeinputmystringatthispoint
    if (answer == "sum") {
      sum(a, sum);
    } else {
      product(a, pr);
    }
  }

  public static void sum(int a, int sum) {
    for (int i = 0; i < a; i++) {
      sum = sum + (a - i);
    }
    System.out.println("The sum of the numbers is " + sum);
  }

  public static void product(int a, int pr) {
    for (int i = 0; i < a; i++) {
      pr = pr * (a - i);
    }
  }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 1
    Welcome to SO! Please take some time to format your code so that it is easier for the community to read and help you. – GrizzlyManBear Feb 03 '16 at 17:05
  • Have a look at the answer to this one http://stackoverflow.com/questions/24336626/in-java-should-i-use-a-different-scanner-instance-for-different-types-of-input?rq=1 – matt freake Feb 03 '16 at 17:06
  • 2
    Re `if (answer=="sum") {`: you should also look at http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Andy Turner Feb 03 '16 at 17:09

2 Answers2

4

After you call int a = sc.nextInt(); you enter an integer in the console and press enter. The integer you entered gets stored in a, whereas the newline character (\n) is read by your String answer = sc.nextLine(); and so it doesn't accept a string from you.

Add this line

sc.nextLine(); // Will read the '\n' character from System.in

after

int a = sc.nextInt();

Another method: You can scan for a string instead of an int and get a by parsing for int:

try {
    int a = Integer.parseInt(sc.nextLine());
}
catch (ParseException ex) { // Catch
}

On another (side) note, do not use if (answer=="sum"), instead you would want to use

if (Object.equals (answer, "sum")

Refer to this.

Community
  • 1
  • 1
Madhav Datt
  • 1,065
  • 2
  • 10
  • 25
3

After this line:

int a = sc.nextInt();

Add this:

sc.nextLine();

The reason you need to add sc.nextLine() is because nextInt() does not consume the newline.

Alternatively, you may scan for a String and parse it to the respective type, for example:

int a = Integer.parseInt(sc.nextLine());

Add: And something not related to your primary question, when comparing the value of a String, use .equals and not ==.

We use == to compare identity, so it should be:

if (answer.equals("sum"))
user3437460
  • 17,253
  • 15
  • 58
  • 106