80 likes | 179 Views
CS 220 Lecture 1. Array Review. Array Example. public class ArrayOperations { int nums[]; int used; public ArrayOperations() { nums = new int[10]; used = 0; } public boolean makeInts(String d) { Scanner s = new Scanner(d); s.useDelimiter(","); used = 0;
E N D
CS 220 Lecture 1 Array Review
Array Example public class ArrayOperations { int nums[]; int used; public ArrayOperations() { nums = new int[10]; used = 0; } public boolean makeInts(String d) { Scanner s = new Scanner(d); s.useDelimiter(","); used = 0; while (used < 10 && s.hasNextInt()) { nums[used] = s.nextInt(); used++; } return !s.hasNextInt(); }
Array Example public int findLargest() { //This method assumes there is at least one element in the array int largest = nums[0]; for (int i = 1; i < used; i++) { if (nums[i] > largest) largest = nums[i]; } return largest; } }
Example GUI import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class ArrayReviewGUI extends JFrame implements ActionListener { JTextField numbers; JLabel numbersLabel; JTextField result; JLabel resultLabel; JButton makeNewArray; JButton clearNumbers; JButton findLargest; JLabel error; ArrayOperations op;
Example GUI public ArrayReviewGUI() { super("Array Review"); setBounds(100, 200, 950, 700); getContentPane().setLayout(null); setVisible(true); numbers = new JTextField(); numbers.setBackground(Color.white); numbers.setBounds(60, 20, 300, 40); add(numbers); numbersLabel = new JLabel("Enter a Comma Delimited Sequence of at Most 10 Numbers", JLabel.CENTER); numbersLabel.setBounds(20, 80, 400, 40); add(numbersLabel); makeNewArray = new JButton("Make Array"); makeNewArray.setBounds(400, 20, 200, 40); makeNewArray.addActionListener(this); add(makeNewArray);
Example GUI clearNumbers = new JButton("Clear Numbers"); clearNumbers.setBounds(700, 20, 200, 40); clearNumbers.addActionListener(this); add(clearNumbers); result = new JTextField(); result.setBackground(Color.white); result.setBounds(60, 160, 100, 40); add(result); resultLabel = new JLabel("Largest Value", JLabel.CENTER); resultLabel.setBounds(60, 220, 100, 40); add(resultLabel); findLargest = new JButton("Find Largest"); findLargest.setBounds(200, 160, 200, 40); findLargest.addActionListener(this); add(findLargest); op = new ArrayOperations(); repaint(); }
Example GUI public void actionPerformed(ActionEvent e) { if (error != null) remove(error); Object b = e.getSource(); if (b == clearNumbers) { numbers.setText(""); result.setText(""); } else if (b == makeNewArray) { if (!op.makeInts(numbers.getText())) { error = new JLabel("Only the first 10 numbers will be used"); error.setBounds(10, 65, 300, 40); error.setForeground(Color.red); add(error); } }
Example GUI else { result.setText(""+op.findLargest()); } repaint(); } public static void main(String[] args) { new ArrayReviewGUI(); } }