Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner String Confusion

Tags:

java

input

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);
    }
  }
}
like image 526
Petros Hatzivasiliou Avatar asked Jan 29 '26 02:01

Petros Hatzivasiliou


2 Answers

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.

like image 164
Madhav Datt Avatar answered Jan 30 '26 17:01

Madhav Datt


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"))
like image 27
user3437460 Avatar answered Jan 30 '26 16:01

user3437460