Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I NEED A URLEXCEPTION CLASS AND FASTFIBSEQUENCE CLASS. I DONT KNOW HOW TO DO IT.

ID: 3821825 • Letter: I

Question

I NEED A URLEXCEPTION CLASS AND FASTFIBSEQUENCE CLASS. I DONT KNOW HOW TO DO IT. JAVA

Each FibSequence class will implement its own next() method and any other methods/instance variables required to create the Fibonacci numbers.

Fastfibsequence will just be faster than recursive.

one or more classes to handle user-defined exceptions

Fibtester:

package fibtester;

// Imported to open files
import java.io.File;
// Imported to use the exception when files are not found
import java.io.FileNotFoundException;
// Imported to write to a file
import java.io.PrintWriter;
// Imported to use the functionality of Array List
import java.util.ArrayList;
// Imported to use the exceptions for integer values
import java.util.NoSuchElementException;
// Imported to use when the array is out of bounds
import java.lang.NullPointerException;
// Imported to take input from the user
import java.util.Scanner;

public class FibTester
{
/**
* @param args will contain the name of the input and output file
*/
public static void main(String[] args)
{
int fibNumber = 0;

double initialTime = 0.0;
double finalTime = 0.0;
double iterativeTime = 0.0;
double recursiveTime = 0.0;

/*
Our table will have a fixed sized of 5 columns but the number of rows
will vary.
*/
final int COLUMNS = 5;
/*
The time will be stored in nanoseconds but the output will be displayed
in milliseconds. To convert, we need the following constant.
*/
final int MILLISECOND = 1000000;
ArrayList<Long> saveFibNumber = new ArrayList<Long>();
  
try
{
File inputFile = new File (args[0]);
/*
The delimeter will be used to ignore everything that is not a number
*/
Scanner inputStream = new Scanner(inputFile).useDelimiter("[^0-9]+" + "^\.*");
PrintWriter outputFile = new PrintWriter(args[1]);   

try
{
fibNumber = inputStream.nextInt();

if (fibNumber >= 0)
{
LoopFib iterativeTest = new LoopFib();
RecursiveFib recursiveTest = new RecursiveFib();

//Start the Timer for Iterative Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.add(iterativeTest.fib(start));
}
// Stop Timer
finalTime = System.nanoTime();
iterativeTime = (finalTime - initialTime) / MILLISECOND;

// Print to outputFile
outputFile.println("Expected Values. Time of execution: " + iterativeTime
+ " milliseconds ");
displayTable(COLUMNS, saveFibNumber, outputFile);
outputFile.println(" ");

// Start the Timer for Recursive Fib
initialTime = System.nanoTime();
for (int start = 0; start < fibNumber; start++)
{
saveFibNumber.set(start, recursiveTest.fib(start));
}
// Stop the Timer
finalTime = System.nanoTime();
recursiveTime = (finalTime - initialTime) / MILLISECOND;

outputFile.println("‘Fast’ recursively-computed Fibonacci numbers. "
+ " Time of execution: " + recursiveTime + " milliseconds ");
displayTable(COLUMNS, saveFibNumber, outputFile);
}
else
{
System.out.println("The input file contains a negative number. "
+ "Change format to a positive integer.");   
}
}
catch (NoSuchElementException exceptionInteger)
{
System.out.println("Make sure the file ONLY contains an Integer");
}
finally
{
outputFile.close();
inputStream.close();
}
}
catch (FileNotFoundException exceptionFile)
{
System.out.println("File not found. Please try again.");
}
catch (NullPointerException exceptionCommandLine)
{
System.out.println("Provide both input and output file names. Please "
+ "try again");
}
}

/**
* This method will display the Fibonacci number to the output file in a
* formated table
* @param COLUMNS How many columns the table will have
* @param saveFibNumber The array containing the Fibonacci number that will
* be printed
* @param out The output file that will be used to print the Fibonacci numbers
*/
public static void displayTable(int COLUMNS, ArrayList<Long> saveFibNumber, PrintWriter out)
{
for (int currentElement = 0; currentElement < saveFibNumber.size(); currentElement++)
{
out.printf("%9d" + " |", saveFibNumber.get(currentElement));
if ((currentElement + 1) % COLUMNS == 0)
{
out.printf(" ");
}
}
}

}

Sequence:

package fibtester;

/**
*
* @author Sal
*/
public interface Sequence {
int next();
}

Recursivefib:

package fibtester;

import java.util.ArrayList;

/**
*
* @author Sal
*/
public class RecursiveFib implements Sequence
{
private ArrayList<Long> storingFibNumber = new ArrayList<Long>();
/*
To calculate the fibonacci number, you need the previous 2 fibonacci numbers
*/
private final int SECONDFIB = 2;

/**
* Method that will calculate the Fibonacci number
* @param fibNumber Which Fibonacci number we want to calculate
* @return the current Fibonacci number
*/
public long fib(int fibNumber)
{
if(storingFibNumber.size() < SECONDFIB)
{
storingFibNumber.add((long)1);
return 1;
}
if (storingFibNumber.size() < fibNumber)
{
return (fib(fibNumber - 1) + fib(fibNumber - SECONDFIB));
}
if (storingFibNumber.size() == fibNumber)
{
storingFibNumber.add(storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB));
return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
}
else
{   
return storingFibNumber.get(fibNumber - 1) + storingFibNumber.get(fibNumber - SECONDFIB);
}
}
}

Loopfib:

package fibtester;

/**
*
* @author Sal
*/
public class LoopFib implements Sequence
{   
public long fib (int fibNumber)
{
if (fibNumber < 2)
{
return 1;
}
else
{
long olderValue = 1;
long oldValue = 1;
long newValue = 1;

for (int fibIteration = 2; fibIteration <= fibNumber; fibIteration++)
{
newValue = oldValue + olderValue;
olderValue = oldValue;
oldValue = newValue;
}
return newValue;
}
}
}

FastFibSequence

package fibtester;

/**
*
* @author Sal
*/
public class FastFibSequence implements Sequence {
  
}

URLException Class:

-Empty-

Explanation / Answer


Client Code
java code

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

/*

  *   *       Please Visit us at codemiles.com     *

  * This Program was Developed by codemiles.com forums Team

  * *           Please Don't Remove This Comment       *

  */

package clientchat;

  

import com.sun.corba.se.spi.activation.RepositoryPackage.ServerDef;

import java.awt.Container;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.ConnectException;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.net.SocketAddress;

import java.net.UnknownHostException;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.Set;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

/**

*

* @author sami

*/

public class myFrame extends JFrame{

     

    /** Creates a new instance of myFrame */

    private JTextArea ChatBox=new JTextArea(10,45);

    private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    private JTextArea UserText = new JTextArea(5,40);

    private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    private JButton Send = new JButton("Send");

    private JButton Start = new JButton("Connect");

    private Client ChatClient;

    private ReadThread myRead=new ReadThread();

    private JTextField Server=new JTextField(20);

    private JLabel myLabel=new JLabel("Server Name :");

    private JTextField User=new JTextField(20);

    private String ServerName;

    private String UserName;

     

     

    public myFrame() {

        setResizable(false);

        setTitle("Client");

        setSize(560,400);

        Container cp=getContentPane();

        cp.setLayout(new FlowLayout());

        cp.add(new JLabel("Chat History"));

        cp.add(myChatHistory);

        cp.add(new JLabel("Chat Box : "));

        cp.add(myUserHistory);

        cp.add(Send);

        cp.add(Start);

        cp.add(myLabel);

        cp.add(Server);

        cp.add(User);

        Send.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                if(ChatClient!=null) {

                     

                    System.out.println(UserText.getText());

                    ChatClient.SendMassage(UserText.getText());

                }

            }

        });

        Start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                ChatClient=new Client();

                ChatClient.start();

            }

        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setVisible(true);

         

         

    }

     

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        new myFrame();

    }

     

     

    public class Client extends Thread {

        private static final int PORT=9999;

        private LinkedList Clients;

        private ByteBuffer ReadBuffer;

        private ByteBuffer writeBuffer;

        private SocketChannel SChan;

        private Selector ReadSelector;

        private CharsetDecoder asciiDecoder;

         

        public Client() {

            Clients=new LinkedList();

            ReadBuffer=ByteBuffer.allocateDirect(300);

            writeBuffer=ByteBuffer.allocateDirect(300);

            asciiDecoder = Charset.forName( "US-ASCII").newDecoder();

        }

         

        public void run() {

             

            ServerName=Server.getText();

            System.out.println(ServerName);

            UserName=User.getText();

             

            Connect(ServerName);

            myRead.start();

            while (true) {

                 

                ReadMassage();

                 

                try {

                    Thread.sleep(30);

                } catch (InterruptedException ie){

                }

            }

             

        }

        public void Connect(String hostname) {

            try {

                ReadSelector = Selector.open();

                InetAddress addr = InetAddress.getByName(hostname);

                SChan = SocketChannel.open(new InetSocketAddress(addr, PORT));

                SChan.configureBlocking(false);

                 

                SChan.register(ReadSelector, SelectionKey.OP_READ, new StringBuffer());

            }

             

            catch (Exception e) {

            }

        }

        public void SendMassage(String messg) {

            prepareBuffer(UserName+" says: "+messg);

            channelWrite(SChan);

        }

         

         

        public void prepareBuffer(String massg) {

            writeBuffer.clear();

            writeBuffer.put(massg.getBytes());

            writeBuffer.putChar(' ');

            writeBuffer.flip();

        }

         

        public void channelWrite(SocketChannel client) {

            long num=0;

            long len=writeBuffer.remaining();

            while(num!=len) {

                try {

                    num+=SChan.write(writeBuffer);

                     

                    Thread.sleep(5);

                } catch (IOException ex) {

                    ex.printStackTrace();

                } catch(InterruptedException ex) {

                     

                }

                 

            }

            writeBuffer.rewind();

        }

         

        public void ReadMassage() {

             

            try {

                 

                ReadSelector.selectNow();

                 

                Set readyKeys = ReadSelector.selectedKeys();

                 

                Iterator i = readyKeys.iterator();

                 

                while (i.hasNext()) {

                     

                    SelectionKey key = (SelectionKey) i.next();

                    i.remove();

                    SocketChannel channel = (SocketChannel) key.channel();

                    ReadBuffer.clear();

                     

                     

                    long nbytes = channel.read(ReadBuffer);

                     

                    if (nbytes == -1) {

                        ChatBox.append("You logged out ! ");

                        channel.close();

                    } else {

                         

                        StringBuffer sb = (StringBuffer)key.attachment();

                         

                        ReadBuffer.flip( );

                        String str = asciiDecoder.decode( ReadBuffer).toString( );

                        sb.append( str );

                        ReadBuffer.clear( );

                         

                         

                        String line = sb.toString();

                        if ((line.indexOf(" ") != -1) || (line.indexOf(" ") != -1)) {

                            line = line.trim();

                             

                            ChatBox.append("> "+ line);

                            ChatBox.append(""+' ');

                            sb.delete(0,sb.length());

                        }

                    }

                }

            } catch (IOException ioe) {

            } catch (Exception e) {

            }

        }

    }

    class ReadThread extends Thread {

        public void run() {

            ChatClient.ReadMassage();

        }

    }

}

- See more at: http://www.codemiles.com/finished-projects/java-chat-t644.html#sthash.LvruBWHQ.dpuf

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

/*

  *   *       Please Visit us at codemiles.com     *

  * This Program was Developed by codemiles.com forums Team

  * *           Please Don't Remove This Comment       *

  */

package clientchat;

  

import com.sun.corba.se.spi.activation.RepositoryPackage.ServerDef;

import java.awt.Container;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.ConnectException;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.net.SocketAddress;

import java.net.UnknownHostException;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.Set;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

/**

*

* @author sami

*/

public class myFrame extends JFrame{

     

    /** Creates a new instance of myFrame */

    private JTextArea ChatBox=new JTextArea(10,45);

    private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    private JTextArea UserText = new JTextArea(5,40);

    private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    private JButton Send = new JButton("Send");

    private JButton Start = new JButton("Connect");

    private Client ChatClient;

    private ReadThread myRead=new ReadThread();

    private JTextField Server=new JTextField(20);

    private JLabel myLabel=new JLabel("Server Name :");

    private JTextField User=new JTextField(20);

    private String ServerName;

    private String UserName;

     

     

    public myFrame() {

        setResizable(false);

        setTitle("Client");

        setSize(560,400);

        Container cp=getContentPane();

        cp.setLayout(new FlowLayout());

        cp.add(new JLabel("Chat History"));

        cp.add(myChatHistory);

        cp.add(new JLabel("Chat Box : "));

        cp.add(myUserHistory);

        cp.add(Send);

        cp.add(Start);

        cp.add(myLabel);

        cp.add(Server);

        cp.add(User);

        Send.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                if(ChatClient!=null) {

                     

                    System.out.println(UserText.getText());

                    ChatClient.SendMassage(UserText.getText());

                }

            }

        });

        Start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                ChatClient=new Client();

                ChatClient.start();

            }

        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setVisible(true);

         

         

    }

     

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        new myFrame();

    }

     

     

    public class Client extends Thread {

        private static final int PORT=9999;

        private LinkedList Clients;

        private ByteBuffer ReadBuffer;

        private ByteBuffer writeBuffer;

        private SocketChannel SChan;

        private Selector ReadSelector;

        private CharsetDecoder asciiDecoder;

         

        public Client() {

            Clients=new LinkedList();

            ReadBuffer=ByteBuffer.allocateDirect(300);

            writeBuffer=ByteBuffer.allocateDirect(300);

            asciiDecoder = Charset.forName( "US-ASCII").newDecoder();

        }

         

        public void run() {

             

            ServerName=Server.getText();

            System.out.println(ServerName);

            UserName=User.getText();

             

            Connect(ServerName);

            myRead.start();

            while (true) {

                 

                ReadMassage();

                 

                try {

                    Thread.sleep(30);

                } catch (InterruptedException ie){

                }

            }

             

        }

        public void Connect(String hostname) {

            try {

                ReadSelector = Selector.open();

                InetAddress addr = InetAddress.getByName(hostname);

                SChan = SocketChannel.open(new InetSocketAddress(addr, PORT));

                SChan.configureBlocking(false);

                 

                SChan.register(ReadSelector, SelectionKey.OP_READ, new StringBuffer());

            }

             

            catch (Exception e) {

            }

        }

        public void SendMassage(String messg) {

            prepareBuffer(UserName+" says: "+messg);

            channelWrite(SChan);

        }

         

         

        public void prepareBuffer(String massg) {

            writeBuffer.clear();

            writeBuffer.put(massg.getBytes());

            writeBuffer.putChar(' ');

            writeBuffer.flip();

        }

         

        public void channelWrite(SocketChannel client) {

            long num=0;

            long len=writeBuffer.remaining();

            while(num!=len) {

                try {

                    num+=SChan.write(writeBuffer);

                     

                    Thread.sleep(5);

                } catch (IOException ex) {

                    ex.printStackTrace();

                } catch(InterruptedException ex) {

                     

                }

                 

            }

            writeBuffer.rewind();

        }

         

        public void ReadMassage() {

             

            try {

                 

                ReadSelector.selectNow();

                 

                Set readyKeys = ReadSelector.selectedKeys();

                 

                Iterator i = readyKeys.iterator();

                 

                while (i.hasNext()) {

                     

                    SelectionKey key = (SelectionKey) i.next();

                    i.remove();

                    SocketChannel channel = (SocketChannel) key.channel();

                    ReadBuffer.clear();

                     

                     

                    long nbytes = channel.read(ReadBuffer);

                     

                    if (nbytes == -1) {

                        ChatBox.append("You logged out ! ");

                        channel.close();

                    } else {

                         

                        StringBuffer sb = (StringBuffer)key.attachment();

                         

                        ReadBuffer.flip( );

                        String str = asciiDecoder.decode( ReadBuffer).toString( );

                        sb.append( str );

                        ReadBuffer.clear( );

                         

                         

                        String line = sb.toString();

                        if ((line.indexOf(" ") != -1) || (line.indexOf(" ") != -1)) {

                            line = line.trim();

                             

                            ChatBox.append("> "+ line);

                            ChatBox.append(""+' ');

                            sb.delete(0,sb.length());

                        }

                    }

                }

            } catch (IOException ioe) {

            } catch (Exception e) {

            }

        }

    }

    class ReadThread extends Thread {

        public void run() {

            ChatClient.ReadMassage();

        }

    }

}