/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sim;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static jdk.nashorn.internal.objects.NativeMath.max;
/**
*
* #author admin
*/
public class Sim {
public String[][] bigramizedWords = new String[500][100];
public String[] words = new String[500];
public File file1 = new File("file1.txt");
public File file2 = new File("file2.txt");
public int tracker = 0;
public double matches = 0;
public double denominator = 0; //This will hold the sum of the bigrams of the 2 words
public double res;
public double results;
public Scanner a;
public PrintWriter pw1;
public Sim(){
intialize();
// bigramize();
results = max(res);
System.out.println("\n\nThe Bigram Similarity value between " + words[0] + " and " + words[1] + " is " + res + ".");
pw1.close();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Sim si=new Sim();
// TODO code application logic here
}
public void intialize() {
int j[]=new int[35];
try {
File file1=new File("input.txt");
File file2=new File("out.txt");
Scanner a = new Scanner(file1);
PrintWriter pw1= new PrintWriter(file2);
int i=0,count = 0;
while (a.hasNext()) {
java.lang.String gram = a.next();
if(gram.startsWith("question")|| gram.endsWith("?"))
{
count=0;
count-=1;
}
if(gram.startsWith("[")||gram.startsWith("answer")||gram.endsWith(" ") )
{
//pw1.println(count);
j[i++]=count;
count=0;
//pw1.println(gram);
//System.out.println(count);
}
else
{
// System.out.println(count);
count+=1;
//System.out.println(count + " " + gram);
}
int line=gram.length();
int sa_length;
//int[] j = null;
int refans_length=j[1];
//System.out.println(refans_length);
for(int k=2;k<=35;k++)
// System.out.println(j[k]);
//System.out.println(refans_length);
for(int m=2;m<=33;m++)
{
sa_length=j[2];
//System.out.println(sa_length);
for(int s=0;s<=refans_length;s++)
{
for(int l=0;l<=sa_length;l++)
{
for (int x = 0; x <= line - 2; x++) {
int tracker = 0;
bigramizedWords[tracker][x] = gram.substring(x, x + 2);
System.out.println(gram.substring(x, x + 2) + "");
//bigramize();
}
// bigramize();
}
}
}
bigramize();
words[tracker] = gram;
tracker++;
}
//pw1.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Sim.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void bigramize() {
//for(int p=0;p<=sa_length;p++)
denominator = (words[0].length() - 1) + (words[1].length() - 1);
for (int k = 0; k < bigramizedWords[0].length; k++) {
if (bigramizedWords[0][k] != null) {
for (int i = 0; i < bigramizedWords[1].length; i++) {
if (bigramizedWords[1][i] != null) {
if (bigramizedWords[0][k].equals(bigramizedWords[1][i])) {
matches++;
}
}
}
}
}
matches *= 2;
res = matches / denominator;
}
}
I have tried the above code for bigramizing the words in the file "input.txt" i have got the result of bigram but i didnt get the similarity value.
for e.g:
input file contains as
answer:
high
risk
simulate
behaviour
solution
set
rules
[2]
rules
outline
high
source
knowledge
[1]
set
rules
simulate
behaviour
in the above example I have to compare the words under answer with every word under [2] as {high,rules} {high,outline} {high,high} {high,source} {high,knowledge} and I have to store the maximum value of the above comparison and again the second word from answer is taken and then similar process is taken. At last, mean of maximum value of each iteration is taken.
Related
I am trying to make a Connect 5 game, where the game logic is held on the server side, with the client side influencing the current game state. So far, I have the game logic implemented and it works just fine if you were to run it. I am running into issues when trying to implement the actual client/server sider of things.
I am not exactly sure how to go about doing it. What I can do at the moment is get the player names and the size of the board. When it comes to actually playing the game, I run into some issues such as keeping the game running and getting the player's move. Currently the server will stop running after a short period of time. I have tried using a while(true) to keep it running but it doesn't seem to work.
Another issue is displaying the actual board on the client side - while I am able to display the board if you were to just play the game from the server class using System.out.println(fiveInARow);, which displays the board after every move. I have tried using How to send String array Object over Socket? to display the board (testing if I can even just get the empty board at the start of the game to display on the client side), I get an error.
Should I be doing something like How to get input from Console in Java Client Server Program to get an input from the user inside the for (int player = 0; moves-- > 0; player = 1 - player)?
UPDATED: So I'm able to make a move and the move will be played accordingly. However, the second player is unable to make a move (unable to enter input on client side after first input).
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class FiveInARow implements Runnable {
private ArrayList<String> playerNames = new ArrayList<String>();
private String currPlayer;
private Socket socket;
private Scanner scanner;
private int width, height;
private static final char[] PLAYERS = { 'X', 'O' };
private char[][] gameBoard;
private int lastCol = -1, lastRow = -1;
public FiveInARow(Socket socket) {
this.socket = socket;
}
/**
*
* #param w - Width
* #param h - Height
* #param p1 - Player 1
* #param p2 - Player 2
*/
public FiveInARow(int w, int h, String p1, String p2) {
width = w;
height = h;
gameBoard = new char[h][];
playerNames.add(p1);
playerNames.add(p2);
for (int i = 0; i < h; i++) {
Arrays.fill(gameBoard[i] = new char[w], '.');
}
}
// Display the game board
public String toString() {
return IntStream.range(0, width).mapToObj(Integer::toString).collect(Collectors.joining("")) + "\n"
+ Arrays.stream(gameBoard).map(String::new).collect(Collectors.joining("\n"));
}
// Get string representation of the row containing the last play of the user
public String horizontal() {
return new String(gameBoard[lastRow]);
}
// Get string representation of the column containing the last play of the user
public String vertical() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
stringBuilder.append(gameBoard[h][lastCol]);
}
return stringBuilder.toString();
}
// Get string representation of the "/" diagonal containing the last play of the
// user
public String fowardSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol + lastRow - h;
if (w >= 0 && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
/**
* Get string representation of the "\" diagonal containing the last play of the
* user
*
* #return
*/
public String backSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol - lastRow + h;
if (0 <= w && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
public static boolean contains(String str, String subString) {
return str.indexOf(subString) >= 0;
}
// Determine if a game as been won
public boolean hasWon() {
if (lastCol == -1) {
System.err.println("No move has been made yet");
return false;
}
char symbol = gameBoard[lastRow][lastCol];
String streak = String.format("%c%c%c%c%c", symbol, symbol, symbol, symbol, symbol);
return contains(horizontal(), streak) || contains(vertical(), streak) || contains(fowardSlashDiagonal(), streak)
|| contains(backSlashDiagonal(), streak);
}
/**
*
* #param symbol - Symbol/piece to be played
* #param scanner - Input
*/
public void playMove(char symbol, Scanner scanner) {
do {
if (symbol == PLAYERS[0]) {
currPlayer = playerNames.get(0);
} else {
currPlayer = playerNames.get(1);
}
System.out.println("\n" + currPlayer + "'s turn: ");
int col = scanner.nextInt();
// Check if input is valid
if (!(0 <= col && col < width)) {
System.out.println("Column must be between 0 and " + (width - 1));
continue;
}
for (int h = height - 1; h >= 0; h--) {
if (gameBoard[h][col] == '.') {
gameBoard[lastRow = h][lastCol = col] = symbol;
return;
}
}
// If column has already been filled, we need to ask for a new input
System.out.println("Column " + col + " is full");
} while (true);
}
// public static void main(String[] args) {
// try (Scanner input = new Scanner(System.in)) {
// String player1Name, player2Name;
// int height = 6;
// int width = 9;
// int moves = height * width;
//
// System.out.println("Player 1 name: ");
// player1Name = input.next();
//
// System.out.println("Player 2 name: ");
// player2Name = input.next();
//
// FiveInARow fiveInARow = new FiveInARow(width, height, player1Name, player2Name);
//
// System.out.println("Enter 0 - " + (width - 1) + " to play a piece\n");
//
// System.out.println(fiveInARow);
//
// for (int player = 0; moves-- > 0; player = 1 - player) {
// char symbol = PLAYERS[player];
//
// fiveInARow.playMove(symbol, input);
//
// System.out.println(fiveInARow);
//
// if (fiveInARow.hasWon()) {
// System.out.println("\nPlayer " + symbol + " wins!");
//
// return;
// }
// }
//
// System.out.println("Game over. Draw game!");
// }
// }
#Override
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
FiveInARow fiveInARow = new FiveInARow(width, height, "Kevin", "Fasha");
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(fiveInARow);
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
fiveInARow.playMove(symbol, scanner);
System.out.println(fiveInARow);
if (fiveInARow.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
public static void main(String[] args) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(59898)) {
System.out.println("The game server is running...");
ExecutorService pool = Executors.newFixedThreadPool(20);
while (true) {
pool.execute(new FiveInARow(serverSocket.accept()));
}
}
}
}
Client
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class FiveInARowClient {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Pass the server IP as the sole command line argument");
return;
}
try (Socket socket = new Socket(args[0], 59898)) {
System.out.println("Enter lines of text then Ctrl+D or Ctrl+C to quit");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
}
}
}
I developed a game and I want to keep track of the Top-3 Best Scores in a file, so that we don't lose the Scores after closing the game. It's not working properly and I don't know why.
- The Best Scores are Integers, and the lowest it is the better. The Best Score is the lowest.
- It is not saving the Scores in ascending Order
It does create a file and it appears to work with the main tests but after a few Scores being add, it does not sort the array in ascending order, so the file is in the wrong way.
package pt.iscte.dcti.poo.sokoban.starter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import pt.iul.ista.poo.utils.Point2D;
public class BestScores {
public int[] bestScore = new int[3];
public final int level;
public BestScores(int level) {
this.level = level;
}
public int[] getBestScore() {
return bestScore;
}
//Register BestScores
public void setBestScore(int score) {
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] == 0) {
bestScore[i] = score;
return;
}
}
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
addBestScore(score);
}
public void addBestScore(int score) {
if(score < bestScore[bestScore.length - 1])
bestScore[bestScore.length - 1] = score;
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
}
public int getTopOne() {
return bestScore[0];
}
public int getLevel() {
return level;
}
//Check if the file exists, else create it
public void searchFile() {
File tmpDir = new File("bestScores/BestScore_" + level + ".txt");
if (!tmpDir.exists())
createOrAddScore();
else {
checkScores(tmpDir);
createOrAddScore();
}
}
//Create file with Scores if they exist.
public void createOrAddScore() {
try {
PrintWriter writer = new PrintWriter(new File("bestScores/BestScore_" + level + ".txt"));
writer.println("BestScores: ************Level:" + level + "************");
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] != 0)
writer.println((i+1) + "º " + bestScore[i] + " " + "moves.");
}
writer.close();
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
}
//Read File and return Best Scores, so that we don't lose the bestScores even after closing the game :D.
public void checkScores(File file) {
int[] array = new int[3];
try {
Scanner scanner = new Scanner(file);
String title_line = scanner.nextLine();
int i = 0;
while(scanner.hasNextLine()) {
String[] line = scanner.nextLine().split(" ");
array[i] = Integer.parseInt(line[1]);
i++;
}
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
for (int i = 0; i < array.length; i++)
if(array[i] != 0)
setBestScore(array[i]);
}
public static void main(String[] args) {
// BestScores bS = new BestScores(4);
//test1 No BEstScores
// bS.searchFile();
//test2 WithBestScores
// bS.setBestScore(40);
// bS.setBestScore(15);
bS.setBestScore(50);
// bS.setBestScore(30);
// bS.setBestScore(10);
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
//test3 With file with Scores
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
}
}
So, i'm having trouble generating random numbers with uniform distribution in java, given the maximum and the minimun value of some attributes in some data set (Iris from UCI for machine learning). What i have is iris dataset, in some 2-d-array called samples. I put the random values according to the maximun and the minimun value of each attribute in iris data set (without the class attribute) in a 2-d-array called gworms (which has some extra fields for some other values of the algorithm).
So far, the full algorithm is not working properly, and my thoughts are in the fact that maybe the gworms (the points in 4-d space) are not generating correctly or with a good randomness. I think that the points are to close to each other (this i think because of some results obtained later whose code is not shown here). So, i'm asking for your help to validate this code in which i implement "uniform distribution" for gworms (for de first 4 positions):
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package glowworms;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Random;
import weka.core.AttributeStats;
import weka.core.Instances;
/**
*
* #author oscareduardo937
*/
public class GSO {
/* ************ Initializing parameters of CGSO algorithm ******************** */
int swarmSize = 1000; // Swarm size m
int maxIte = 200;
double stepSize = 0.03; // Step size for the movements
double luciferin = 5.0; // Initial luciferin level
double rho = 0.4; // Luciferin decay parameter
double gamma = 0.6; // Luciferin reinforcement parameter
double rs = 0.38; // Initial radial sensor range. This parameter depends on the data set and needs to be found by running experiments
double gworms[][] = null; // Glowworms of the swarm.
/* ************ Initializing parameters of clustering problem and data set ******************** */
int numAtt; // Dimension of the position vector
int numClasses; // Number of classes
int total_data; //Number of instances
int threshold = 5;
int runtime = 1;
/*Algorithm can be run many times in order to see its robustness*/
double minValuesAtts[] = new double[this.numAtt]; // Minimum values for all attributes
double maxValuesAtts[] = new double[this.numAtt]; // Maximum values for all attributes
double samples[][] = new double[this.total_data][this.numAtt]; //Samples of the selected dataset.
ArrayList<Integer> candidateList;
double r;
/*a random number in the range [0,1)*/
/* *********** Method to put the instances in a matrix and get max and min values for attributes ******************* */
public void instancesToSamples(Instances data) {
this.numAtt = data.numAttributes();
System.out.println("********* NumAttributes: " + this.numAtt);
AttributeStats attStats = new AttributeStats();
if (data.classIndex() == -1) {
//System.out.println("reset index...");
data.setClassIndex(data.numAttributes() - 1);
}
this.numClasses = data.numClasses();
this.minValuesAtts = new double[this.numAtt];
this.maxValuesAtts = new double[this.numAtt];
System.out.println("********* NumClasses: " + this.numClasses);
this.total_data = data.numInstances();
samples = new double[this.total_data][this.numAtt];
double[] values = new double[this.total_data];
for (int j = 0; j < this.numAtt; j++) {
values = data.attributeToDoubleArray(j);
for (int i = 0; i < this.total_data; i++) {
samples[i][j] = values[i];
}
}
for(int j=0; j<this.numAtt-1; j++){
attStats = data.attributeStats(j);
this.maxValuesAtts[j] = attStats.numericStats.max;
this.minValuesAtts[j] = attStats.numericStats.min;
//System.out.println("** Min Value Attribute " + j + ": " + this.minValuesAtts[j]);
//System.out.println("** Max Value Attribute " + j + ": " + this.maxValuesAtts[j]);
}
//Checking
/*for(int i=0; i<this.total_data; i++){
for(int j=0; j<this.numAtt; j++){
System.out.print(samples[i][j] + "** ");
}
System.out.println();
}*/
} // End of method InstancesToSamples
public void initializeSwarm(Instances data) {
this.gworms = new double[this.swarmSize][this.numAtt + 2]; // D-dimensional vector plus luciferin, fitness and intradistance.
double intraDistance = 0;
Random r = new Random(); //Random r;
for (int i = 0; i < this.swarmSize; i++) {
for (int j = 0; j < this.numAtt - 1; j++) {
//Uniform randomization of d-dimensional position vector
this.gworms[i][j] = this.minValuesAtts[j] + (this.maxValuesAtts[j] - this.minValuesAtts[j]) * r.nextDouble();
}
this.gworms[i][this.numAtt - 1] = this.luciferin; // Initial luciferin level for all swarm
this.gworms[i][this.numAtt] = 0; // Initial fitness for all swarm
this.gworms[i][this.numAtt + 1] = intraDistance; // Intra-distance for gworm i
}
//Checking gworms
/*for(int i=0; i<this.swarmSize; i++){
for(int j=0; j<this.numAtt+2; j++){
System.out.print(gworms[i][j] + "** ");
}
System.out.println();
}*/
} // End of method initializeSwarm
}
The main class is this one:
package uniformrandomization;
/**
*
* #author oscareduardo937
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import weka.core.Instances;
import glowworms.GSO;
public class UniformRandomization {
public UniformRandomization(){
super();
}
//Loading the data from the filename file to the program. It can be .arff or .csv
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("File not found: " + filename);
}
return inputReader;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
BufferedReader datafile1 = readDataFile("src/data/iris.arff");
Instances data = new Instances(datafile1);
GSO gso = new GSO();
gso.instancesToSamples(data);
gso.initializeSwarm(data);
System.out.println("Fin...");
}
}
So i want to know if with this code, the numbers of the position ij of the gworms are generating within the range of max value and min value for attribute j.
Thanks so much in advanced.
Since my last text and question was very vague here is my source as of now and a clearer question. It is all about the padding now.
Here is my code up to now:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class makeTable {
static ArrayList<String> val1 = new ArrayList<>(Arrays.asList("field1", "field1val2", "field1val3"));
static ArrayList<String> val2 = new ArrayList<>(Arrays.asList("field2", "field2val2", "field2val3"));
static int col1=15;
static int col2=15;
public static void main(String arg[]) {
BufferedWriter writeTable = null;
try {
writeTable = new BufferedWriter(new FileWriter("C:/testtable.txt"));
//Anfang erste Zeile
writeTable.write("+ ");
for (int i = 0; i < col1; i++){
writeTable.write("-");
}
writeTable.write(" + ");
for (int i = 0; i < col2; i++){
writeTable.write("-");
}
writeTable.write(" +");
writeTable.newLine();
//Ende erste Zeile
for (int i = 0; i < val1.size(); i++){
writeTable.write("| " + val1.get(i) + " "+ " + " +" "+ val2.get(i) + " "+ " |");
writeTable.newLine();
writeTable.write("+ ");
for (int j = 0; j < col1; j++){
writeTable.write("-");
}
writeTable.write(" + ");
for (int m = 0; m < col2; m++){
writeTable.write("-");
}
writeTable.write(" +");
writeTable.newLine();
}
} catch (IOException e) {
System.err.println(e);
} finally {
if (writeTable != null) {
try {
writeTable.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
}
Now I need to add a padding so that the result looks like :
+ -------------- + -------------- +
| field1 | filed2 |
+ -------------- + -------------- +
| field1val2 | field2val2 |
+ -------------- + -------------- +
and so on. It need to be centered. I can only think of adding something like val1.get(i).length() /2 and that is the amount of " " to add.... but how can I do that?
I cannot use other libraries (3rd party ones).
Here are the results of your program after I centered the text.
+ -------------- + -------------- +
| field1 + field2 |
+ -------------- + -------------- +
| field1val2 + field2val2 |
+ -------------- + -------------- +
| field1val3 + field2val3 |
+ -------------- + -------------- +
Here are the changes I made.
The biggest thing that I did was break your monolithic code into methods. By writing small methods, you can break your larger task into smaller tasks. The smaller tasks are easier to code.
A class name starts with a capital letter. I renamed makeTable to MakeTable.
I changed your code to use the List interface, rather than the ArrayList class. By using the interface, it makes it easier in the future to change the type of List. I can use a LinkedList by changing 2 lines of your code.
The main method now just creates the output. I couldn't write directly to the C drive on my Windows 8.1 laptop. I had to create the file in the same directory as the code.
The writeDashedLine method writes a dashed line. I use the code in 2 places, but by putting the code into a method, I only had to write the code once.
The writeDashes method writes the dashes part of a dashed line. Again, I use the code in 2 places, but by putting the code into a method, I only had to write the code once.
The writeValueLine method writes the values on a line. I use the code in one place, but to be consistent with the writeDashedLine method, I wrote a method for the code.
The rest of the methods are what I wrote to center text. First, I found the longest value in the 2 lists of values. Next, I added the 4 characters of padding. Next, I centered the text by adding padding to the front and the back of the String.
Study these methods so you can do this type of task in the future.
Here's the formatted code.
package com.ggl.testing;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MakeTable {
static List<String> val1 = new ArrayList<>(Arrays.asList("field1",
"field1val2", "field1val3"));
static List<String> val2 = new ArrayList<>(Arrays.asList("field2",
"field2val2", "field2val3"));
static int length = getLongestValue(val1, val2) + 4;
public static void main(String arg[]) {
BufferedWriter writeTable = null;
try {
writeTable = new BufferedWriter(new FileWriter("testtable.txt"));
writeDashedLine(writeTable);
writeTable.newLine();
// Ende erste Zeile
for (int i = 0; i < val1.size(); i++) {
writeValueLine(writeTable, val1.get(i), val2.get(i));
writeTable.newLine();
writeDashedLine(writeTable);
writeTable.newLine();
}
} catch (IOException e) {
System.err.println(e);
} finally {
if (writeTable != null) {
try {
writeTable.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
public static void writeDashedLine(BufferedWriter writeTable)
throws IOException {
// Anfang erste Zeile
writeTable.write("+ ");
writeDashes(writeTable);
writeTable.write(" + ");
writeDashes(writeTable);
writeTable.write(" +");
}
public static void writeDashes(BufferedWriter writeTable)
throws IOException {
for (int i = 0; i < length; i++) {
writeTable.write("-");
}
}
public static void writeValueLine(BufferedWriter writeTable, String value1,
String value2) throws IOException {
writeTable.write("| " + centerText(value1, length) + " + "
+ centerText(value2, length) + " |");
}
public static String centerText(String text, int length) {
int textLength = text.length();
if (textLength > length) {
return text.substring(0, length);
} else if (textLength == length) {
return text;
} else {
int diff1 = (length - textLength) / 2;
int diff2 = length - textLength - diff1;
return getPadding(' ', diff1) + text + getPadding(' ', diff2);
}
}
public static String getPadding(char pad, int length) {
String padding = "";
for (int i = 0; i < length; i++) {
padding += pad;
}
return padding;
}
public static int getLongestValue(List<String> val1, List<String> val2) {
int length = 0;
for (String s : val1) {
length = Math.max(length, s.length());
}
for (String s : val2) {
length = Math.max(length, s.length());
}
return length;
}
}
In the code below change append with StringBuilder with BufferedWriter.
public void appendCentered(StringBuilder sb, String s, int width) {
if (s.length() > width) {
s = s.substring(0, width);
}
int spaces = width - s.length();
int before = spaces / 2;
int after = spaces - before; // Could be 1 more than 'before'.
appendSpaces(sb, before);
sb.append(s);
appendSpaces(sb, after);
}
public void appendSpaces(StringBuilder sb, int width) {
while (width-- > 0) {
sb.append(' ');
}
}
I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}