2017-01-26 3 views
0

Логика, которую я пытаюсь построить, заключается в том, что пользователь собирает четыре общих членства, консоль будет печатать, что они достигли четырех, но они все еще могут продолжаться, если они захотят.одна и та же строка в нескольких циклах не решена

Если они решили остановиться в четыре, они должны ввести «quit». Проблема возникает во втором цикле с операторами if else. Я получаю сообщение об ошибке «aff не может быть разрешено».

import java.util.Scanner; 

public class Seption { 

    public static void main(String[] args) { 

     System.out.println("Welcome back!");  

     Scanner userName = new Scanner(System.in); 
     System.out.println("Username: "); 
     String username = userName.next(); 

     Scanner passWord = new Scanner(System.in); 
     System.out.println("Password: "); 
     String password = passWord.next(); 

     int affCount = 0; 

     while (affCount <= 4) { 

      Scanner newAff = new Scanner(System.in); 
      System.out.println("enter new affiliate"); 
      String aff = newAff.nextLine(); 

      System.out.println("Alright, " + aff + " is now your new affiliate!"); 

      affCount = affCount + 1; 
      System.out.println("You now have " + affCount + " affiliates"); 

      if (affCount == 4) { 

       System.out.println("Congratulations! You've accumulated 4 affiliates!" 
        + " any new affiliates added to this branch will be extra earnings" 
        + " You can also make a new branch and start over" 
        + " To quit this branch, Type 'quit'"); 

      continue; 
      } 
     } 

     while (affCount > 4) { 

      if (aff.equals("quit") == false) { 

       Scanner newAff = new Scanner(System.in); 
       System.out.println("enter new affiliate"); 
       String aff = newAff.nextLine(); 

       System.out.println("Alright, " + aff + " is now your new affiliate!"); 

       affCount = affCount + 1; 
       System.out.println("You now have " + affCount + " affiliates"); 

      } 

      else if (aff.equals("quit")) { 

       System.out.println("This branch is now over"); 
       break; 
      } 
     } 

    } 

} 
+5

Это из области видимости. Вам нужно объявить 'aff' вне петель. – shmosel

ответ

0

Вы должны просто создать экземпляр Scanner из System.in один раз и использовать тот же экземпляр, в любом месте, что вам нужно, чтобы получить ввод от пользователя:

public static void main(String[] args){ 
System.out.println("Welcome back!");  
Scanner scanner = new Scanner(System.in); 
System.out.println("Username: "); String 
username = scanner.next(); 
System.out.println("Password: "); 
String password = scanner.next(); 
int affCount = 0; 
String aff = ""; 
while (affCount <= 4) { 
    System.out.println("enter new affiliate");  
    aff = scanner.nextLine(); 
    System.out.println("Alright, " + aff + " is now your new affiliate!"); 
    affCount = affCount + 1; 
    System.out.println("You now have " + affCount + " affiliates"); 
    if (affCount == 4) 
     { 
     System.out.println("Congratulations! You've accumulated 4 affiliates!" + " any new affiliates added to this branch will be extra earnings" + " You can also make a new branch and start over" + " To quit this branch, Type 'quit'"); 
     continue; 
     } 
    } 

    while (affCount > 4) { 
     if (aff.equals("quit") == false) 
      { 
       System.out.println("enter new affiliate"); 
       aff = scanner.nextLine(); 
       System.out.println("Alright, " + aff + " is now your new affiliate!"); 
       affCount = affCount + 1; 
       System.out.println("You now have " + affCount + " affiliates"); 
       } 
      else if (aff.equals("quit")) 
        { 
        System.out.println("This branch is now over"); 
        break; } 
      } 
    } 
+0

Благодарим вас за помощь. Я ввел исправления, но теперь он дает мне ошибку «Локальная переменная aff может быть не инициализирована». Это появляется только для операторов if else в последнем цикле while. –

+1

Да, видимо, кто-то предложил изменить мой ответ и сменить код. Когда вы создаете экземпляр 'aff', инициализируете его:' String aff = "" '... Ответ должен быть исправлен сейчас !! –

+0

Теперь это сработало. Спасибо за помощь! –

Смежные вопросы