Home > OS >  How do you connect a single scanner to two arrays?
How do you connect a single scanner to two arrays?

Time:12-14

Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this

int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
    
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
    
int midterm[] = new int[8];
int grades[] = new int[8];
    
{ 
  if ( record == 1 )
    System.out.println("Enter 8 subjects and their corresponding grades:");

  System.out.println();
    
  int i = 0;
    
  for( i = 0; i < 8; i   )
  {   
    System.out.println(subjects[i]);                               
    System.out.print("Enter Grade: ");               
    grades[i] = scangrades.nextInt();            
    if( i == ( subjects.length) )
      System.out.println();
  }
  System.out.println("Enter Grade Successful");       
}

If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.

If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!

CodePudding user response:

Break out the grade collection into a new function, and pass along the array you want to collect the grades into.

    public static void main(String[] args) throws IOException {

        int gradeType = 0;

        // Use a single scanner for all input
        Scanner aScanner = new Scanner(System.in);

        System.out.println("Press 1 to Record for Midterm");
        System.out.println("Press 2 to Record for Final Term");
        gradeType = aScanner.nextInt();

        String[] subjects = { "Subject A", "Subject B" };
        int[] midtermGrades = new int[subjects.length];
        int[] finalGrades = new int[subjects.length];

        int[] gradesToCollect;

        // Use gradesToCollect to reference the array you want to
        // collect into.
        //
        // Alternatively, we could call collectGrades() in both the if/else
        // condition
        if (gradeType == 1) {
            gradesToCollect = midtermGrades;
        } else {
            gradesToCollect = finalGrades;
        }

        collectGrades(subjects, gradesToCollect, aScanner);

        System.out.println("\n\nThese are the collected grades");
        System.out.println("Mid  Final");
        for (int i = 0; i < subjects.length; i  ) {
            System.out.format("=  =\n", midtermGrades[i], finalGrades[i]);
        }
    }

    // Collect a grade for each subject into the given grades array.
    public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {

        System.out.format("Enter %s subjects and their corresponding grades:",
                subjects.length);
        System.out.println();

        for (int i = 0; i < subjects.length; i  ) {
            System.out.format("Enter Grade for %s : ", subjects[i]);
            grades[i] = scn.nextInt();
            if (i == (subjects.length))
                System.out.println();
        }
        System.out.println("Enter Grade Successful");
    }


CodePudding user response:

    class Main {

        public static final Scanner in = new Scanner(System.in);

        public static void main(String[] args) {
            in.useDelimiter("\r?\n");
            Student student = new Student();

            System.out.println("Press 1 to Record for Midterm");
            System.out.println("Press 2 to Record for Final Term");
            int record = in.nextInt();

            if (record == 1) {
                student.setTerm(TermType.MID);
                System.out.println("Enter 8 subjects and their corresponding grades:");
                System.out.println("Enter Subject and grades space separated.  Example -  \nMaths 79");
                System.out.println();


                for (int i = 0; i < 8; i  ) {
                    System.out.println("Enter Subject "   (i   1)   " details");
                    String subjectAndGrade = in.next();

                    int index = subjectAndGrade.lastIndexOf(" ");
                    String subject = subjectAndGrade.substring(0, index);
                    int grade = Integer.parseInt(subjectAndGrade.substring(index   1));
                    student.getSubjects().add(new Subject(grade, subject));
                }
                System.out.println("Enter Grade Successful");

                System.out.println("========================================================");
                System.out.println("Details: ");

                System.out.println("Term Type "   student.getTerm());
                for(int i = 0; i< student.getSubjects().size(); i  ) {
                    System.out.println("Subject: "   student.getSubjects().get(i).getSubjectName()   ", Grade: "   student.getSubjects().get(i).getGradeScore());
                }
            }
        }
    }

    class Student {
        private List<Subject> subjects = new ArrayList<>();
        private TermType term;

        public List<Subject> getSubjects() {
            return subjects;
        }

        public void setSubjects(List<Subject> subjects) {
            this.subjects = subjects;
        }

        public TermType getTerm() {
            return term;
        }

        public void setTerm(TermType term) {
            this.term = term;
        }
    }

    class Subject {
        private int gradeScore;
        private String subjectName;

        public Subject(int gradeScore, String subjectName) {
            this.gradeScore = gradeScore;
            this.subjectName = subjectName;
        }

        public double getGradeScore() {
            return gradeScore;
        }

        public void setGradeScore(int gradeScore) {
            this.gradeScore = gradeScore;
        }

        public String getSubjectName() {
            return subjectName;
        }

        public void setSubjectName(String subjectName) {
            this.subjectName = subjectName;
        }
    }

scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.

  • Related