2015-09-06 115 views
-1

我是新来的编程和我正在做一个简单的缺勤计划,但我坚持,如果有人输入一个值不是缺席或T参加。下面是代码:如何让用户再次输入相同变量的值?

package loops; 
import java.util.Scanner; 

public class Students_Absence { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter T for the attended student and A for the absent"); 
     System.out.print("Student1:"); 
     char student1 = input.next().charAt(0); 

     if (student1 =='T' || student1 == 'A'){ 
      System.out.println(); 
     } else { 
      System.out.println("The sympol you entered is incorrect, please use either T or A"); 
      char student1 = input.next().charAt(0); 
     } 

     input.close(); 
    } 
} 

我希望用户重新输入值,如果他错过,点击或东西,而随后重新启动整个程序。但是当我尝试时,我得到(重复的局部变量)错误。

谢谢!

回答

3

你不需要重新声明变量,只是重新分配给它(在标线):

student1 = input.next().charAt(0); 

无论如何,你应该实现它作为一个循环,因为用户可以输入一个错误的值再次...

0

你似乎宣布student1两次,一次在if语句之前,另一次在else。考虑在else块中重用student1变量。

else { 
    System.out.println("The sympol you entered is incorrect, please use either T or A"); 
    student1 = input.next().charAt(0); 
} 
0

你不必在你的else块再次使用char类型:

System.out.println("The sympol you entered is incorrect, please use either T or A"); 
student1 = input.next().charAt(0); 

的错误出现,因为你要创建同一个变量两次(如果您之前使用char您正在创建一个新变量的变量的名称),并且您只需再次分配它的值(使用变量的名称,但没有关键字char),而不是重新创建它。

相关问题