我有一个程序,当用户输入c时需要继续

时间:2016-04-01 13:16:17

标签: java loops

import java.util.Scanner;
 public class Example {
 public static void main(String[] args) {
  Scanner keyboardInput = new Scanner(System.in);
  String inputString;
   char flag = 'y';
   int number = 0;
   int sum = 0;
    while(flag = 'c' && flag = 'C') {
    System.out.print("Enter number to be added");
    number = keyboardInput.nextInt();
    System.out.println("You have entered " + number);
    sum = 0;
     for(int i = 0; i < number; i++) {
     sum = sum + i + 1;
}
     System.out.println("The sum from 1 to " + number + " is " + sum);
     System.out.print("Enter c or C to quit or any other key to continue:");
      keyboardInput.nextLine();
      inputString = keyboardInput.nextLine();
     flag = inputString.charAt(0);
 }
 } 
}

以下是我所知道的代码,除了我需要让程序只在输入字符c时继续,而不是在输入c时结束

1 个答案:

答案 0 :(得分:1)

尝试c使用flag而不是y,如下所示:

  char flag = 'c';

在你的while循环中使用==

   while(flag == 'c' || flag == 'C') {