java - 我想采用字符串输入来继续条件分支

标签 java string

我想从键盘输入一个字符串。但是当我运行这个程序时,没有选择接受字符串输入。我不知道我的错是什么。

我的代码是:

import java.util.Scanner;
public class Input_Program {
public static void main(String args[])
{
    Scanner in = new Scanner(System.in);
    int a,b;
    System.out.println("Enter the first number :");
    a=in.nextInt();
    System.out.println("Enter the second number :");
    b=in.nextInt();


    System.out.println("Value of first number:"+a);
    System.out.println("Value of second number:"+b);

    System.out.println("Do you want Add two numbers");
    System.out.println("To Continue: Type Yes");

    String S=in.nextLine();

    if("Yes".equals(S)||"yes".equals(S))
    {   
    int sum=a+b;
    System.out.println("Summation :"+sum);  
    }

}  
}

我想从此代码中获取输入。但它不起作用。

    String S=in.nextLine();

    if("Yes".equals(S)||"yes".equals(S))
    {   
    int sum=a+b;
    System.out.println("Summation :"+sum);  
    }  

这段代码的结果是:

run:
Enter the first number :
2
Enter the second number :
3
Value of second number:3
Do you want the Summation of two numbers
To Continue: Type Yes

构建成功(总时间:9秒)

最佳答案

1) nextLine() 根据https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html “使扫描仪前进到当前行并返回跳过的输入”,这不是您正在寻找的行为。

2)看来你是java新手,有命名约定。变量名请勿以大写字母开头

3)我修复了你的缩进,并且还概括了输入以接受以 y 开头的任何内容。将来请确保以这种方式编写代码,因为可以更轻松地判断哪些代码行位于 if 语句、循环等中。

import java.util.Scanner;
public class Input_Program {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the first number :");
        int a = in.nextInt();
        System.out.println("Enter the second number :");
        int b = in.nextInt();


        System.out.println("Value of first number:" + a);
        System.out.println("Value of second number:" + b);

        System.out.println("Do you want Add two numbers");
        System.out.println("To Continue: Type Yes");

        String s = in.next();

        if(s.toLowerCase().contains("y")){   
            int sum=a+b;
            System.out.println("Summation :"+sum);  
        }

    }  
}

关于java - 我想采用字符串输入来继续条件分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747257/

相关文章:

python - 类型错误 : Can't convert 'int' object to str implicitly Python 3

Java SystemTray 图标并不总是有效

java - JAXB Umarshaller 错误

java - 使用 jmf 自动重复播放视频

jquery - 如何检查和删除字符串中的 html 标签

java - 仅从字符串中提取字符并将其存储在另一个字符串中

python - 如何检查字符串是否包含子字符串的所有字符?

javascript - 使用 Javascript 将数据库日期转换为短日期

java - 在 Activity 中使用 Thread 计算整数并在 View 中更新 Canvas

java - Tomcat sh脚本权限