알고리즘

Java Programming 3

이온시옥 2018. 11. 22. 02:40
반응형
  1. First, write a function
    class Solution { public int solution(int[] A); }

    that, given a zero-indexed array A consisting of N integers, returns the number of distinct values in array A. For example, given array A consisting of six elements such that:

    A[0] = 5 A[1] = 1 A[2] = 1 A[3] = 5 A[4] = 7 A[5] = 1

    the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 5 and 7. Finally, write a simple program that tests your function.


    package assignment;


    import java.util.ArrayList;

    public class Solution {

    public int solution(int[] A) {

    ArrayList<Integer> array = new ArrayList<Integer> ();

    for(int i=0; i<A.length; i++) {

    if(!array.contains(A[i])) {

    array.add(A[i]);

    }

    }

    return array.size();

    }

    public static void main(String[] args) {

    //test case array

    int[] arr = {1,2,3,3,4,1,2,3,4,4,5,4,3,2};

    //print array values

    System.out.print("Array values: ");

    for (int i=0; i<arr.length; i++) {

    System.out.print( arr[i] + ", ");

    }

    System.out.print("\n");

    //new object of Solution

    Solution a = new Solution();

    int result = a.solution(arr); //using solution function

    //print result

    System.out.println("Distinct value: " + result);

    }

    }




  2. Draw a face that represents your feeling. You can make your eyes, nose, mouth and face using different GUI methods. For example, if you feel happy, your face can be drawn as follows.

page1image31037456


package assignment;


import java.awt.*;

import javax.swing.*;


import java.util.*;


public class assignment extends JPanel{

public void paintComponent(Graphics g) {

//draw face

g.setColor(Color.ORANGE);

g.fillOval(120, 20, 200, 220); //draw fill circle

g.setColor(Color.YELLOW);

g.fillRect(220, 140, 10, 30); //draw fill rectangle

g.fillOval(160, 80, 50, 50); 

g.fillOval(240, 80, 50, 50);

g.drawArc(160, 140, 120, 70, 180, 180); //draw arc

}

public static void main(String[] args) {

JFrame frame = new JFrame("Frame"); //make new frames

frame.setSize(500,500); //set the frame size

assignment draw = new assignment(); //save the JPanel drawing Graphics

frame.add(draw); //add the draw to the frame

frame.setVisible(true); //display it

}


}


  1. Write your own chat client and server programs by using the codes in the textbook. Your program should satisfy the following requirements.

    1. Your chat client program should provide some GUI.

    2. Your chat client program should use some multithreading.

    3. Compared to the codes in textbook, your program should be improved in several ways. For example, the participants could be identified by name, one person could send a private message to another person, etc. (Note: Explain the points you improved in your document.)

      SimpleChatClient.java

      package assignment;


      import java.io.*;

      import java.net.*;

      import javax.swing.*;

      import java.awt.*;

      import java.awt.event.*;


      public class SimpleChatClient {

      JTextArea incoming;

      JTextField outgoing;

      BufferedReader reader;

      PrintWriter writer;

      Socket sock;

      JFrame frame;

      public static void main(String[] args) {

      SimpleChatClient client = new SimpleChatClient();

      client.go();

      }

      public void go() {

      frame = new JFrame("Chat client");

      JPanel mainPanel = new JPanel();

      incoming = new JTextArea(20,30);

      incoming.setLineWrap(true);

      incoming.setWrapStyleWord(true);

      incoming.setEditable(false);

      incoming.setCaretPosition(incoming.getDocument().getLength());

      JScrollPane qScroller = new JScrollPane(incoming);

      qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

      qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

      JLabel lbl = new JLabel("Text to send : ");

      outgoing = new JTextField(23);

      lbl.setLabelFor(outgoing);


      JButton sendButton = new JButton("Send");

      sendButton.addActionListener(new SendButtonListener());

      mainPanel.add(qScroller);

      mainPanel.add(lbl);

      mainPanel.add(outgoing);

      mainPanel.add(sendButton);

      setUpNetworking();

      Thread readerThread = new Thread(new IncomingReader());

      readerThread.start();

      frame.getContentPane().add(BorderLayout.CENTER, mainPanel);

      frame.setSize(400, 500);

      frame.setVisible(true);

      }

      private void setUpNetworking() {

      try {

      sock = new Socket("127.0.0.1", 5000); //new socket

      InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());

      reader = new BufferedReader(streamReader);

      writer = new PrintWriter(sock.getOutputStream());

      System.out.println("Networking established");

      frame.setTitle("Chat Client ["+sock.getPort()+"]");

      } catch(IOException ex){

      ex.printStackTrace();

      }

      }

      public class SendButtonListener implements ActionListener{

      public void actionPerformed(ActionEvent ev) {

      try {

      writer.println(outgoing.getText());

      writer.flush();

      } catch(Exception ex){

      ex.printStackTrace();

      }

      outgoing.setText("");

      outgoing.requestFocus();

      }

      }

      public class IncomingReader implements Runnable{

      public void run() {

      String message;

      try {

      while((message = reader.readLine()) != null) {

      System.out.println("Read " + message);

      incoming.append(message + "\n");

      }

      } catch(Exception ex) {

      ex.printStackTrace();

      }

      }

      }

      }


      VerySimpleChatServer.java

      package assignment;


      import java.io.*;

      import java.net.*;

      import java.util.*;

      import javax.swing.*;

      import java .awt.*;


      public class VerySimpleChatServer {


      ArrayList clientOutputStreams;

      JTextArea text;

      public class ClientHandler implements Runnable {

      BufferedReader reader;

      Socket sock;

      public ClientHandler(Socket clientSocket) {

      try {

      sock = clientSocket;

      InputStreamReader isReader = new InputStreamReader(sock.getInputStream());

      reader = new BufferedReader(isReader);

      }

      catch(Exception ex) {

      ex.printStackTrace();

      }

      }

      public void run() {

      String message;

      try {

      while((message = reader.readLine()) != null) {

      System.out.println("read " + message);

      tellEveryone("[" + sock.getPort() + "] : " + message);

      }

      catch(Exception ex) {

      ex.printStackTrace();

      }

      }

      }

      public static void main (String[]args) {

      new VerySimpleChatServer().go();

      }

      public void go() {

      clientOutputStreams = new ArrayList();

      JFrame frame = new JFrame("Server Chat");

      frame.setSize(380, 500);

      JPanel mainPanel = new JPanel();

      text = new JTextArea(20,20);

      text.setLineWrap(true);

      text.setWrapStyleWord(true);

      text.setEditable(false);

      JScrollPane scroll = new JScrollPane(text);

      scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

      scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

      text.setCaretPosition(text.getDocument().getLength());

      mainPanel.add(scroll);

      frame.getContentPane().add(BorderLayout.CENTER, mainPanel);

      frame.setVisible(true);

      try {

      ServerSocket serverSock = new ServerSocket(5000); //new server socket to Port: 5000 (fixed)

      System.out.println("Server started");

      text.append("Server started \n");

      while(true) {

      Socket clientSocket = serverSock.accept(); //accept client

      //print out accept information.

      System.out.println("New Client Accept! \n IP address and Port number: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());

      text.append("New Client Accept! \n IP address and Port number: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "\n");


      PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());

      clientOutputStreams.add(writer);

      Thread t = new Thread(new ClientHandler(clientSocket));

      t.start();

      System.out.println("got a connection");

      }

      } catch(Exception ex) {

      ex.printStackTrace();

      }

      }

      public void tellEveryone(String message) {

      Iterator it = clientOutputStreams.iterator();

      while(it.hasNext()) {

      try {

      PrintWriter writer = (PrintWriter) it.next();

      writer.println(message);

      writer.flush();

      }

      catch(Exception ex) {

      ex.printStackTrace();

      }

      }

      }

      }



  2. Write a GUI program that is used to order something in the restaurant. Your program should show some items such as Pizza, Oil pasta, Seafood pasta, Fried rice, and Noodle with their prices. If you choose some items and then push a button, the total price should be calculated. Here is an example of this program.

2011-12345 Kim

page2image4160512

Pizza
Oil pasta Seafood pasta Fried rice Noodle

10,000 7,500 8,000 6,000 4,000

page2image4160128 page2image4154560 page2image4153792page2image4156480 page2image4156096page2image4156672 page2image4156864

Total is 20,000.


package assignment;


import javax.swing.*;

import java.awt.*;


import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;


public class assignment {

JFrame frame;

JLabel Label_high;

JLabel Label_low;

Draw draw;

int mouse_x;

int mouse_y;

boolean pizza = false;

boolean oil = false;

boolean seafood = false;

boolean fried = false;

boolean noodle = false;

boolean drinks = false;


public static void main(String args[]) {

assignment menu = new assignment();

menu.go();

}

public void go() {

frame = new JFrame("Menu");

Label_high = new JLabel("Menu");

Label_high.setVisible(true);


draw = new Draw();

Label_low = new JLabel();

Label_low.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


frame.getContentPane().add(BorderLayout.NORTH, Label_high);

frame.getContentPane().add(BorderLayout.CENTER, draw);

frame.getContentPane().add(BorderLayout.SOUTH, Label_low);

frame.setSize(250, 300);


frame.setVisible(true);

draw.addMouseListener(new MouseClick());

}

class MouseClick implements MouseListener {

public void mouseClicked(MouseEvent ev) {

mouse_x=ev.getX();

    mouse_y=ev.getY();

   

draw.repaint();

}


@Override

public void mouseEntered(MouseEvent e) {

// TODO Auto-generated method stub

}


@Override

public void mouseExited(MouseEvent e) {

// TODO Auto-generated method stub

}


@Override

public void mousePressed(MouseEvent e) {

// TODO Auto-generated method stub

}


@Override

public void mouseReleased(MouseEvent e) {

// TODO Auto-generated method stub

}

}

@SuppressWarnings("serial")

class Draw extends JPanel{

public void paintComponent(Graphics g) {

super.paintComponent(g);


int total = 0;

int y_index = 25;

//pizza

g.drawString("Pizza", 50, y_index+10);

g.drawString("10,000", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

pizza = !pizza;

}

if (pizza) {

g.fillRect(25, y_index, 10, 10);

total += 10000;

}

else g.drawRect(25, y_index, 10, 10);

//Oil pasta

y_index+=25;

g.drawString("Oil pasta", 50, y_index+10);

g.drawString("7,500", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

oil = !oil;

}

if (oil) {

g.fillRect(25, y_index, 10, 10);

total += 7500;

}

else g.drawRect(25, y_index, 10, 10);

//Seafood Pasta

y_index+=25;

g.drawString("Seafood pasta", 50, y_index+10);

g.drawString("8,000", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

seafood = !seafood;

}

if (seafood) {

g.fillRect(25, y_index, 10, 10);

total += 8000;

}

else g.drawRect(25, y_index, 10, 10);

//Fried Rice

y_index+=25;

g.drawString("Fried rice", 50, y_index+10);

g.drawString("6,000", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

fried = !fried;

}

if (fried) {

g.fillRect(25, y_index, 10, 10);

total += 6000;

}

else g.drawRect(25, y_index, 10, 10);

//Noodle

y_index+=25;

g.drawString("Noodle", 50, y_index+10);

g.drawString("4,000", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

noodle = !noodle;

}

if (noodle) {

g.fillRect(25, y_index, 10, 10);

total += 4000;

}

else g.drawRect(25, y_index, 10, 10);

//Drinks

y_index+=25;

g.drawString("Drinks", 50, y_index+10);

g.drawString("1,000", 160, y_index+10);

if( 25 < mouse_x && mouse_x < 35 ) {

if( y_index < mouse_y && mouse_y < y_index+10)

drinks = !drinks;

}

if (drinks) {

g.fillRect(25, y_index, 10, 10);

total += 1000;

}

else g.drawRect(25, y_index, 10, 10);

Label_low.setText("Total is " + total); //print total

}

}

}



  1. Write a panel with a JTextArea where the user can enter some text. The panel should have a button. When the user clicks on the button, the panel should count the number of lines in the user's input, the number of words in the user's input, and the number of characters in the user's input. This information should be displayed on three labels in the panel. Scrollbars should appear when the user types more text than will fit in the available area. Here is an example of this program.


    package assignment;


    import javax.swing.*;

    import java.awt.*;

    import java.awt.event.*;


    public class assignment implements ActionListener {

    JButton button;

    JTextArea text;

    JLabel lines;

    JLabel words;

    JLabel chars;

    public static void main(String [] args) {

    assignment gui = new assignment(); 

    gui.go();

    }

    public void go() {

    //new frame

    JFrame frame = new JFrame("Word Counter");

    //new two panel

    JPanel panel_text = new JPanel();

    JPanel panel_bottom = new JPanel();

    //BOXLayout for panel_bottom

    panel_bottom.setLayout(new BoxLayout(panel_bottom, BoxLayout.Y_AXIS));

    //top label with number and name

    JLabel top = new JLabel("Word Counter");

    //new textarea for user

    text = new JTextArea(17, 30);

    panel_text.add(text);

    //scroller for textarea

    JScrollPane scroller = new JScrollPane(text);

    text.setLineWrap(true);

    scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    panel_text.add(scroller);

    //buttom for process check

    button = new JButton("Process the text");

    button.addActionListener(this);

    //label of line, word, char

    lines = new JLabel("   Number of lines: ");

    words = new JLabel("   Number of words: ");

    chars = new JLabel("   Number of chars: ");

    //add the button & labels in a bottom

    panel_bottom.add(button);

    panel_bottom.add(lines);

    panel_bottom.add(words);

    panel_bottom.add(chars);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //quit windows then terminate program

    frame.getContentPane().add(BorderLayout.NORTH, top); //top

    frame.getContentPane().add(BorderLayout.CENTER, panel_text); //middle

    frame.getContentPane().add(BorderLayout.SOUTH, panel_bottom); //bottom

    frame.setSize(400, 400);

    frame.setVisible(true);

    }

    public void actionPerformed(ActionEvent ev) {

    //when click the button, calculate all the lines, words, and chars

    lines.setText("   Number of lines:  " + calculateLines());

    words.setText("   Number of words:  " + calculateWords());

    chars.setText("   Number of chars:  " + calculateChars());

    }

    public int calculateLines( ) {

    String user_text = text.getText();

    String[] lines = user_text.split("\r\n|\r|\n");

    return lines.length;

    }

    public int calculateWords( ) {

    String user_text = text.getText();

    String[] words = user_text.split(" ");

    return words.length;

    }

    public int calculateChars( ) {

    return text.getText().length();

    }

    }



  2. Write a program that prints a list of files in a directory specified by the user. Some files in the directory might themselves be directories, and the subdirectories can themselves contain directories. In other words, your program should list all the files in a directory and all its subdirectories, to any level of nesting.

page3image14421248



package assignment;


import java.io.*;

import java.util.*;

public class assignment {

public static void main(String [] args) {

String input_path;

Scanner scan = new Scanner(System.in);

System.out.print("Path: ");

input_path = scan.nextLine();

System.out.print("\n");

new assignment().path(input_path);

}

public void path(String input_dir) {

File file;

File dir = new File(input_dir);

File[] list = dir.listFiles();

for(int i=0; i<list.length; i++) {

file = list[i];

if(file.isFile()) {

System.out.println("File --> " + file.getAbsolutePath());

}

}

for(int i=0; i<list.length; i++) {

file = list[i];

if(file.isDirectory()) {

System.out.println("Directory --> " + file.getAbsolutePath());

path(file.getAbsolutePath()); //recursive call function

}

}

}

}




반응형