Java 扫描字符串混淆

Java 扫描字符串混淆,java,input,Java,Input,程序应该允许我输入一个值和一个字符串。当涉及到字符串时,它允许我输入整数,但它打印问题,但不允许我输入任何内容 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.nextI

程序应该允许我输入一个值和一个字符串。当涉及到字符串时,它允许我输入整数,但它打印问题,但不允许我输入任何内容

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);
    }
  }
}
import java.util.Scanner;
公共类PrSumN{
公共静态void main(字符串参数[]){
System.out.println(“输入值”);
扫描仪sc=新的扫描仪(System.in);
int a=sc.nextInt();
整数和=0;
int-pr=1;
System.out.println(“您想要数字的总和还是数字的乘积?”);
字符串应答=sc.nextLine();
//这一点并不妨碍我输入我的字符串
如果(答案=“总和”){
sum(a,sum);
}否则{
产品(a、pr);
}
}
公共静态无效和(整数a,整数和){
for(int i=0;i
在这一行之后:

int a = sc.nextInt();
添加以下内容:

sc.nextLine();
需要添加
sc.nextLine()
的原因是
nextInt()
不使用换行符

或者,您可以扫描字符串并将其解析为相应的类型,例如:

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

添加:与主要问题无关的内容,在比较字符串值时,使用
.equals
和not
=

我们使用
==
来比较身份,因此应该是:

if (answer.equals("sum"))

调用
int a=sc.nextInt()之后在控制台中输入一个整数,然后按enter键。输入的整数存储在
a
中,而换行符(
\n
)由
字符串answer=sc.nextLine()读取,因此它不接受您的字符串

添加这一行

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

int a = sc.nextInt();
另一种方法:您可以扫描
字符串而不是
int
,然后通过解析
int
,获得
a

在另一个(侧面)注释中,不要使用
if(answer==“sum”)
,而要使用

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

请参阅。

欢迎来到SO!请花一些时间格式化您的代码,以便社区更容易阅读和帮助您。请看一下这篇文章的答案:if(answer==“sum”){
:您还应该看一下注意事项,您实际上不需要使用
Object.equals
,因为两个参数都不是空的-您可以使用
answer.equals(“sum”)
(或
“总和”。等于(答案)
)。这是真的-谢谢
if (Object.equals (answer, "sum")