在Java中循环问题

时间:2018-04-08 11:00:14

标签: java while-loop do-loops

我尝试运行的do-while代码存在问题。我希望它重复添加用户生成的两个数字之和的过程,但代码不会因某些原因而运行。我是java编程和循环的新手。我只是想弄清楚为什么代码不会运行并重复输入数字和添加总和的过程。我不打算比较字符串,我的主要目标是让while循环重复添加用户产生的两个数字的过程,如果他们用Y回答。谢谢!

   import java.util.Scanner;
 public class Try {

public static void main(String[] args) {
    int first;
    int second;
    int sum; 
    String repeat;
    Scanner kbd= new Scanner(System.in);
    do { 
    System.out.print("Enter the first number: "); 
    first = kbd.nextInt(); 

    System.out.print("Enter the second number: "); 
    second = kbd.nextInt(); 

    sum = first + second; 
    System.out.println("The sum is:" +sum ); 
    System.out.print("Do you want to do this again? Y or N? "); 
    repeat= kbd.nextLine();
    } while (repeat=="y" || repeat=="Y");


    }


}

1 个答案:

答案 0 :(得分:0)

repeat变量的数据类型更改为char

将此repeat= kbd.nextLine();行替换为repeat = kbd.next().charAt(0);

将此while (repeat=="y" || repeat=="Y");替换为while (repeat == 'y' || repeat == 'Y');