ILoveJava's Profile User Rating: -----

Reputation: 29 Craftsman
Group:
Active Members
Active Posts:
391 (0.4 per day)
Joined:
12-March 12
Profile Views:
6,189
Last Active:
User is offline Jun 15 2014 03:40 PM
Currently:
Offline

Previous Fields

Country:
AU
OS Preference:
Windows
Favorite Browser:
Chrome
Favorite Processor:
Intel
Favorite Gaming Platform:
PC
Your Car:
Who Cares
Dream Kudos:
0

Latest Visitors

Icon   ILoveJava Java <3

Posts I've Made

  1. In Topic: Printing altered arraylist

    Posted 7 Jun 2014

    Bump for a very frustrated student.
  2. In Topic: Printing altered arraylist

    Posted 5 Jun 2014

    Okay, I worked out what was wrong with my code, and now everything is being sent down properly, and I think I've done what you suggested, pbl. In my bubbleSort method it takes a 'type' String, which then sends the data to it's respected switch case.
    I'm having a very small issue with my bubbleSort method now that I've "fixed" it to accept the ArrayList data, that now it will only sort the first 2 rows in the ArrayList data. I'm not really sure what I can do to fix this.
    package assessment.pkg3;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.InputMismatchException;
    import java.util.Scanner;
    /**
     *
     * @author Nathan
     */
    public class Assessment3 {
        /**
         * @param args the command line arguments
         */   
        
        // Initialize ArrayList<Students>
        static ArrayList<Students> studentsList = new ArrayList<Students>();  
        static ArrayList<Students> studentsBySurname = new ArrayList<Students>();
        static ArrayList<Students> studentsById = new ArrayList<Students>();
        
        public static void main(String[] args) throws FileNotFoundException, InputMismatchException, IOException {    
            // Initialize instance variables
            String surname;
            String givenNames;
            String prefName;
            int studentId;
            boolean fullTime;
            String contactNumber;
            boolean loveJava;
            String diploma;
            
            // Declare file variables for handling reading in, and printing out.
            File inFile = new File("students.txt");
            File idFile = new File("byId.txt");
            File surnameFile = new File("bySurname.txt");
            
            FileWriter surnameOut = new FileWriter(surnameFile);
            FileWriter idOut = new FileWriter(idFile);
            
            Scanner sc = new Scanner(inFile);
            sc.useDelimiter(",");
            
            while(sc.hasNext()) {
                surname = sc.next();
                givenNames = sc.next();
                prefName = sc.next();
                studentId = sc.nextInt();
                fullTime = sc.nextBoolean();
                contactNumber = sc.next();
                loveJava = sc.nextBoolean();
                diploma = sc.next();
                studentsList.add(new Students(surname.trim(), givenNames, prefName, studentId, fullTime, contactNumber, loveJava, diploma));
                studentsBySurname.add(new Students(surname.trim(), givenNames, prefName, studentId, fullTime, contactNumber, loveJava, diploma));
                studentsById.add(new Students(surname.trim(), givenNames, prefName, studentId, fullTime, contactNumber, loveJava, diploma));
            }
            sc.close();            
            // Parse studentList arrayList to the bubbleSort method
            bubbleSort(studentsList, "surname");
            bubbleSort(studentsList, "id");   
            
            // Print original ArrayList
            System.out.println("Original");
            for(int i = 0; i < studentsList.size(); i++) {
                System.out.println(studentsList.get(i).toString());
            }
            
            // Print contents of the sorted ArrayList's
            System.out.println("Surname");
            for (int i = 0; i < studentsBySurname.size(); i++) {
                System.out.println(studentsBySurname.get(i).toString());
                surnameOut.write(studentsBySurname.get(i).toString() + "\n");
            }
            System.out.println("id");       
            for (int i = 0; i < studentsById.size(); i++) {
                System.out.println(studentsById.get(i).toString());
                idOut.write(studentsById.get(i).toString() + "\n");
            }
            surnameOut.close();
            idOut.close();
        }
        
        // bubbleSort method for sorting ArrayList data sent down.
    	// case "id" will sort the data by the studentId variable.
    	// case "surname" will sort the data by the surname variable.
        public static void bubbleSort(ArrayList<Students> array, String type) throws IOException {
            // Declare instance variables
            int oCounter;
            int iCounter;
            Students element;
            
            try {
                switch(type) {
                    case "id":
                        for(oCounter = 0; oCounter < array.size() - 1; oCounter++) {
                            for(iCounter = 0; iCounter < array.size() - 1 - oCounter; iCounter++) {
                                if(array.get(iCounter).getStudentId() < array.get(iCounter+1).getStudentId()){
                                    element = array.get(iCounter);
                                    studentsById.set(iCounter, array.get(iCounter + 1));
                                    studentsById.set(iCounter + 1, element);
                                }
                            }
                        }
                    break;
    
                    case "surname":
                        for(oCounter = 0; oCounter < array.size() - 1; oCounter++) {
                            for(iCounter = 0; iCounter < array.size() - 1 - oCounter; iCounter++) {
                                if(array.get(iCounter).getSurname().compareToIgnoreCase(array.get(iCounter+1).getSurname()) > 0) { 
                                    element = array.get(iCounter);
                                    studentsBySurname.set(iCounter, array.get(iCounter + 1));
                                    studentsBySurname.set(iCounter + 1, element);
                                }
                            }
                        }
                    break;
                }
            } catch(IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
    
  3. In Topic: Printing altered arraylist

    Posted 29 May 2014

    On closer inspection, I've misread the project brief. Instead of parsing just the student id into the bubble sort, I need to parse the entire arraylist, then sort it all by the studentid, then print it to a text file.
    I've yet to work out the rest of it, but i've changed the bubbleSort method to
    public static void bubbleSort(Students[] array) {
    

    but now I'm getting errors on some of my if statements as below.
                    if(array[iCounter + 1] > array[iCounter]){
                        element = array[iCounter];
                        array[iCounter] = array[iCounter + 1];
                        array[iCounter + 1] = element;
    


    NetBeans is just giving me "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: assessment.pkg3.Assessment3.bubbleSort
    at assessment.pkg3.Assessment3.main(Assessment3.java:57)" as the error.

    Has anyone had to do this kind of thing before?
  4. In Topic: ComboBox used as an InputBox

    Posted 23 Apr 2014

    Sorry, I didn't realise I was so vague in my original post. I will provide the code I have below.

    It is for a kind of.. teacher's console written in Visual Basic, where they can add/remove students, search for them, mark tests for certain students, and then display those marks. Now I want to just restrict the mark tests sub, so it has to pick a student id from the Hashtable hshStudents, and if there are no id's, then it will make them add one to the database.
    I hope that makes sense.

    Public Class Main
        Dim hshStudents As New Hashtable()
        Dim hshMarks As New Hashtable()
    
        'Index changed event to handle the background changes.
        'Every time this sub is activated it will set the BackgroundImage and BackColor to Nothing (null), in order to prevent labels carrying different colors from previous selections.
        Private Sub cmbBgColour_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBgColour.SelectedIndexChanged
            Me.BackgroundImage = Nothing
            Me.BackColor = Nothing
    
            If cmbBgColour.Text = "Red" Then
                Me.BackColor = Color.Red
            ElseIf cmbBgColour.Text = "Blue" Then
                Me.BackColor = Color.Blue
            ElseIf cmbBgColour.Text = "Special" Then
                Me.BackgroundImage = My.Resources.batman
            End If
        End Sub
    
        'User input for adding students to the Hashtable.
        'Accepts a student id as the Hashtable key, and a full name for the value.
        'Restricts adding to only one ID being present in the table at a time, as multiple people can't use the same id.
        'Allows adding of multiple duplicate names as names can be very common.
        Sub AddStudent()
            Dim fname As String
            Dim id As String
    
            id = InputBox("Enter student ID")
            For Each element As DictionaryEntry In hshStudents
                If element.Key.Equals(id) Then
                    MsgBox("That Student ID is already present in the database. Please try again")
                    id = InputBox("Enter student ID")
                End If
            Next
    
            fname = InputBox("Enter student full name")
    
            hshStudents.Add(id, fname)
        End Sub
    
        'Allows the user to search for students stored in the HashTable.
        'Accepts only Student ID input, then scans the HashTable for a match.
        'If a match is found, it will output the Student ID again, and also the student's name.
        'If a match is not found, it will display an error message.
        Sub SearchStudents()
            Dim id As String
            Dim msg As String = ""
    
            id = InputBox("Enter student ID")
    
            For Each element As DictionaryEntry In hshStudents
                If element.Key.Equals(id) Then
                    msg = vbNewLine & element.Key & " - " & element.Value
                ElseIf element.Key <> id Then
                    msg = vbNewLine & "Student not found!"
                End If
            Next
    
            MsgBox("Searching for student """ & id & """..." & vbNewLine & msg)
    
        End Sub
    
        'Allows the end-user (teacher) to mark tests completed by the student.
        'Accepts Student ID and Student Mark inputs, then adds them to a new HashTable called hshMarks.
        Sub MarkTests()
            Dim id As String
            Dim mark As String
    
            If (hshStudents.Count = 0) Then
                MsgBox("There are no students that can be marked.")
            Else
                id = InputBox("Enter student id")
                mark = InputBox("Enter student mark")
    
                hshMarks.Add(id, mark)
            End If
        End Sub
    
        'Allows end-user to display marks for a selected student.
        Sub DisplayMarks()
            Dim id As String
            Dim msg As String = ""
    
            id = InputBox("Enter student ID")
    
            For Each element As DictionaryEntry In hshMarks
                If element.Key.Equals(id) Then
                    msg = vbNewLine & element.Key & " scored " & element.Value & "%."
                ElseIf element.Key <> id Then
                    msg = vbNewLine & "Marks not found!"
                End If
            Next
    
            MsgBox("Searching for student " & id & "'s test score..." & vbNewLine & msg)
        End Sub
    
        'Allows end-user to remove students from the HashTable.
        Sub RemoveStudent()
            Dim id As String
    
            id = InputBox("Enter student ID")
            For Each element As DictionaryEntry In hshStudents
                If element.Key <> id Then
                    MsgBox("That Student ID doesn't not exist in the HashTable. Please try again.")
                    id = InputBox("Enter student ID")
                End If
            Next
            hshStudents.Remove(id)
        End Sub
    
        Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
            SearchStudents()
        End Sub
    
        Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
            AddStudent()
        End Sub
    
        Private Sub btnMark_Click(sender As Object, e As EventArgs) Handles btnMark.Click
            MarkTests()
        End Sub
    
        Private Sub btnMarksDisp_Click(sender As Object, e As EventArgs) Handles btnMarksDisp.Click
            DisplayMarks()
        End Sub
    
        Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
            RemoveStudent()
        End Sub
    End Class
    
  5. In Topic: CandyMachine project, don't know where to start

    Posted 15 Apr 2014

    Okay, so I've done a bit of the program (probably more than a bit, but you know), but I'm running into an error as below.

    Quote

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:504)
    at java.lang.Integer.parseInt(Integer.java:527)
    at candymachine.CandyMachine.sellProduct(CandyMachine.java:103)
    at candymachine.CandyMachine.actionPerformed(CandyMachine.java:75)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.window.dispatchEventImpl(window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

    The method code is as below.
        private void sellProduct(Dispenser product, String productName){
            double coinsInserted = 0;
            double price;
            double productPrice;
            int choice;
    
            String str = "";
    
            if (product.getCount() > 0){
                price = product.getProductCost();
                productPrice = price - coinsInserted;
    
                while(productPrice > 0) {
                    choice = JOptionPane.showConfirmDialog(null, productName + " costs " + productPrice + ".\nThere are " + product.getCount() + " left", "Purchase Confirmation", JOptionPane.INFORMATION_MESSAGE);
                    
                    if(choice == JOptionPane.YES_OPTION) {
                        coinsInserted = coinsInserted + Integer.parseInt(str);
                        productPrice = price - coinsInserted;
                    } else {
                        str = "Hello";
                    }
                }
    
                cashRegister.acceptAmount((int)coinsInserted);
                product.makeSale();
                JOptionPane.showMessageDialog(null, "Your candy has been vendored");
            } else {
                // If dispenser is empty.
                JOptionPane.showMessageDialog(null, productName + " is sold out. Please make another selection");
            }
        }
    


    I know there are errors in the code, which I'm fixing, I just need this error fixed before I can go in and try out some solutions.

My Information

Member Title:
D.I.C Regular
Age:
20 years old
Birthday:
August 16, 1994
Gender:
Location:
Australia
Full Name:
Nathan Kreider
Years Programming:
1
Programming Languages:
Theoretical Programming

Contact Information

E-mail:
Private

Comments

Page 1 of 1
  1. Photo

    AnalyticLunatic Icon

    30 Aug 2012 - 13:17
    Professional Chef, eh? Have any recipes worth sharing?
Page 1 of 1