2015-10-06 2 views
-2

Я застрял на этом. Что мне делать, чтобы запускать каждый элемент моего массива в моем методе askQuizQuestion?Скукивание с несколькими методами при сохранении количества

Это простая викторина, но я проиграл, чтобы инициализировать каждый элемент массива в моем методе askQuizQuestion.

Каждый ответ использования - это либо да, либо нет. Если да, то +1 к текущему счету, и после последнего вопроса общее количество возвращается к методу printSurveyResults для определения ответа на печать.

public class Quiz { 

public static void printSurveyResults(int answerCount) 
{ 

if (answerCount >= 0 && answerCount <= 2) 
    {System.out.println ("You are more exhausted than stressed out.");} 

else if (answerCount >= 3 && answerCount <= 5) 
    {System.out.println ("You are beginning to stress out.");}  

else if (answerCount >= 6 && answerCount <= 8) 
    {System.out.println ("You are possibly stressed out.");} 

else if (answerCount >= 9 && answerCount <= 12) 
    {System.out.println ("You are probably stressed out.");} 
}   

public static int askQuizQuestion(String prompt, Scanner keyboard) 
     { 
    int count = 0; 
    int i; 
    for (i = 0; i < 12; i++); 
      System.out.println(prompt); 
      if (keyboard.equals("yes")) 
      {count++;} 

      printSurveyResults(count); 
    } 



public static void main(String[] args) 
    { 

    String[] question = new String[12]; 
    question [0] = "I find myself less eager to go back to work or to resume my chores after a weekend."; 
    question [1] = "I feel less and less patient and/or sympathetic listening to other people’s problems."; 
    question [2] = "I ask more “closed-ended questions to discourage dialogue with friends and co-workers than “open-ended” ones to encourage it."; 
    question [3] = "I try to get away from people as soon as I can."; 
    question [4] = "My dedication to work, exercise, diet, and friendships is waning."; 
    question [5] = "I am falling further behind in many of the responsibilities in my life."; 
    question [6] = "I am losing my sense of humor."; 
    question [7] = "I find it more and more difficult to see people socially."; 
    question [8] = "I feel tired most of the time."; 
    question [9] = "I don’t seem to have much fun anymore."; 
    question [10] = "I feel trapped. "; 
    question [11] = "I know what will make me feel better, but I just can’t push myself to do it and I’ll “Yes, but” any suggestions that people make."; 


    } 

}

+0

Может быть [для цикла] (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) может помочь – MadProgrammer

+0

для-петли был вставлен, но как я вызывать каждый вопрос в методе? – SpiveyAtticus

+0

Вы используете 'for-loop' и передаете каждый элемент как' prompt' – MadProgrammer

ответ

0

Найдите ниже код с небольшим рефакторинга. Кажется, ваша задача - считывать пользовательский ввод в Java. Этот поток SO: How can I get the user input in Java показывает различные методы для этого. Я использовал метод next() из класса Scanner в коде ниже.

import java.util.Scanner; 

public class Quiz { 

    private static final String[] questions = {"I find myself less eager to go back to work or to resume my chores after a weekend.", 
      "I feel less and less patient and/or sympathetic listening to other people’s problems.", 
      "I ask more “closed-ended questions to discourage dialogue with friends and co-workers than “open-ended” ones to encourage it.", 
      "I try to get away from people as soon as I can.", 
      "My dedication to work, exercise, diet, and friendships is waning.", 
      "I am falling further behind in many of the responsibilities in my life.", 
      "I am losing my sense of humor.", 
      "I find it more and more difficult to see people socially.", 
      "I feel tired most of the time.", 
      "I don’t seem to have much fun anymore.", 
      "I feel trapped. ", 
      "I know what will make me feel better, but I just can’t push myself to do it and I’ll “Yes, but” any suggestions that people make."}; 

    public static void printSurveyResults(int answerCount) { 

     if (answerCount >= 0 && answerCount <= 2) { 
      System.out.println("You are more exhausted than stressed out."); 
     } else if (answerCount >= 3 && answerCount <= 5) { 
      System.out.println("You are beginning to stress out."); 
     } else if (answerCount >= 6 && answerCount <= 8) { 
      System.out.println("You are possibly stressed out."); 
     } else if (answerCount >= 9 && answerCount <= 12) { 
      System.out.println("You are probably stressed out."); 
     } 
    } 


    public static void main(String[] args) { 
     Scanner reader = new Scanner(System.in); // Reading from System.in 
     String response; 
     int count = 0; 
     for (int i = 0; i < questions.length; i++) { 
      System.out.println(questions[i]); 
      response = reader.next(); 
      if (response.equals("yes")) { 
       count++; 
      } 
     } 
     printSurveyResults(count); 

    } 

} 
+0

СПАСИБО !!!! Я делал все в неправильном порядке вместе со списком других вопросов. Я могу следовать этому, хотя. – SpiveyAtticus

+0

хорошо, это подразумевает, что он решает вашу проблему? В качестве альтернативы вы можете сохранить свою функцию 'askQuizQuestion' и передать индекс каждого элемента в массиве: ' for (int i = 0; i pelumi

+0

Да, это решило мою проблему. Итерация массива превзошла меня, потому что я поставил массив под основной, когда ему нужен собственный метод для вызова. Затем итерация через массив. Еще раз спасибо. – SpiveyAtticus

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