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(' ');
}
}
Related
This is the code I atempted with the guide of external video which didnt cover expected output in terms of formatting
public class Lab3Class {
public static void main(String[] args) {
// TODO Auto-generated method stub
int table = 1;
while(table<10) {
int i = 1;
while(i<=10)
{
System.out.println(table+ " * "+i+" = "+(table*i));
i++;
}
System.out.println(" ");
table++;
}
}
}
You are just missing a check for even numbers i.e. if (table % 2 == 0).
public class Main {
public static void main(String[] args) {
int table = 1;
while (table < 10) {
if (table % 2 == 0) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
}
System.out.println();
table++;
}
}
}
Alternatively, you can start table with 2 and increment it by 2 in each iteration as follows:
public class Main {
public static void main(String[] args) {
int table = 2;
while (table < 10) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
System.out.println();
table += 2;
}
}
}
If you need to print it in a tabular structure, you can write the loops as follows:
public class Main {
public static void main(String[] args) {
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + "*" + line + "=" + (i * line) + "\t");
}
System.out.println();
}
}
}
Output:
2*1=2 4*1=4 6*1=6 8*1=8 10*1=10
2*2=4 4*2=8 6*2=12 8*2=16 10*2=20
2*3=6 4*3=12 6*3=18 8*3=24 10*3=30
2*4=8 4*4=16 6*4=24 8*4=32 10*4=40
2*5=10 4*5=20 6*5=30 8*5=40 10*5=50
2*6=12 4*6=24 6*6=36 8*6=48 10*6=60
2*7=14 4*7=28 6*7=42 8*7=56 10*7=70
2*8=16 4*8=32 6*8=48 8*8=64 10*8=80
2*9=18 4*9=36 6*9=54 8*9=72 10*9=90
2*10=20 4*10=40 6*10=60 8*10=80 10*10=100
As you can see, it looks cleaner by using a for loop. However, I recommend you also practice it with a while loop. Once you gain more confidence, I also recommend you use String::format or System.out.printf for better formatting.
This is a very small data set but if the dataset is huge, you can improve the performance by reducing the I/O operation. For this, you can append the result to a StringBuilder and print it just once at the end.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
sb.append(i).append('*').append(line).append('=').append(i * line).append('\t');
}
sb.append('\n');
}
System.out.println(sb);
}
}
I made an RSA Encrypt/Decrypt GUI program with JavaFX.
It seems works well with generating Public and Private keys, but somehow Decryption does not return the plain text I encrypted.
I dunno why this happens, maybe I am misunderstanding the RSA algorithm, so please find ANY problems my code has.
The text file Pnumlist contains the list of Prime numbers I copied from Wikipedia.
I set Private key as n, e and Public key as n, d.
As I know if we set Plain text as M and Crypted text as C, (integer).
C = M^e (mod n)
M = C^d (mod n)
Am I right?
public class Main extends Application {
static int[] arr = new int[120000];
private static int n;
private static int e;
private static int d;
private static int C;
private static int M;
private static int n1;
private static int n2;
private static void SWAPint(int a, int b) {
if(a < b) {
int tmp = a;
a = b;
b = tmp;
}
}
private static int getd() {
int D;
for(D = 1; D < n-1; D++) {
if((e * D) % (n - 1) == 1) {
break;
}
}
return D;
}
private static int GCDr(int a, int b) {
if(b == 0) {
return a;
} else {
return GCDr(b, a%b);
}
}
private static int getCoprime(int E) {
int j;
for(j = 2; j < E; j++) {
if(GCDr(E, j) == 1) {
break;
}
}
return j;
}
private static void keymaker() {
File f = new File("Pnumlist.txt");
try {
Scanner scan = new Scanner(f);
int i = 0;
while(scan.hasNext()) {
arr[i] = scan.nextInt();
i++;
}
int Pnum[] = new int[i];
for(int j = 0; j < Pnum.length; j++) {
Pnum[j] = arr[j];
}
Random slct = new Random();
n1 = Pnum[slct.nextInt(Pnum.length)];
n2 = Pnum[slct.nextInt(Pnum.length)];
SWAPint(n1, n2);
n = n1 * n2;
int Onum = (n1 - 1) * (n2 - 1);
e = getCoprime(Onum);
d = getd();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void start(Stage primaryStage) {
try {
// some javafx stuff...
Encrypt.setOnAction(rct -> {
String tmpP = Ptext.getText();
console.appendText("Input Integer: " + tmpP + "\n");
console.appendText("--------Process--------" + "\n");
M = Integer.parseInt(tmpP);
keymaker();
console.appendText("generated primes: " + n1 + ", " + n2 + "\n");
console.appendText("Calculated key n: " + n + "\n");
console.appendText("Calculated key e: " + e + "\n");
console.appendText("Calculated key d: " + d + "\n");
C = (int) Math.pow(M, e) % n;
console.appendText("--------Crypted Integer--------" + "\n");
console.appendText(Integer.toString(C));
});
Decrypt.setOnAction(rct -> {
String tmpP = Ctext.getText();
console.appendText("\n\nInput Integer: " + tmpP + "\n");
console.appendText("--------Process--------" + "\n");
console.appendText("--------Decrypted Integer--------" + "\n");
int cusM = (int) Math.pow(C, d) % n;
console.appendText(Integer.toString(cusM));
});
// some more javafx stuff...
} catch(Exception e) {
e.printStackTrace();
}
}
// some other javafx methods...
}
need some help with a maze solving program in java.
The program has to read a maze from a file, store it into an array, solve it, and display the solution in a drawing panel. I'm struggling storing it into an array, and I'm really unsure of how to move into solving it and displaying it. But if i could get some help on the array part to get into a groove, I'd really appreciate it.
Here is an example of an input file. I want it to work for any maze of this structure, (with +, -, S, E, and |). The first two numbers, (8, 10) represent the height and width, the # of rows and # of columns.
8 10
+-+-+-+-+-+-+-+-+-+
| |
+ +-+-+-+ +-+-+-+ +
| | | |
+ + +-+-+-+-+-+ + +
| | | | | |
+ + + +-+-+-+ + + +-+
| | | | | | | S|
+ + + + +-+ + + + +-+
| | | |E| | | |
+ + + +-+ +-+ + + +
| | | | | |
+ + +-+-+-+-+-+ + +
| | | |
+ +-+-+-+-+-+-+-+ +
| |
+-+-+-+-+-+-+-+-+-+
Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeSolver {
// The name of the file describing the maze
static String mazefile;
static int width;
static int height;
public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args)) {
readMazeFile(mazefile);
DrawMaze.draw();
if (solveMaze())
System.out.println("Solved!");
else
System.out.println("Maze has no solution.");
}
else {
System.out.println("The arguments are invalid.");
}
}
// Handle the input arguments
static boolean handleArguments(String[] args) {
if (args.length > 4 || args.length < 1) {
System.out.println("There are too many or too few command line arguments");
return false;
}
if (args.length == 1) {
String mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
return true;
}
if (args.length == 2) {
String mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
if (cellsize < 10) {
return false;
}
return true;
}
if (args.length == 3) {
String mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
int borderwidth = Integer.parseInt(args[2]);
if (borderwidth < 5) {
return false;
}
return true;
}
if (args.length == 4) {
String mazefile = args[0];
File file = new File(mazefile);
if (!file.canRead()) {
return false;
}
int cellsize = Integer.parseInt(args[1]);
int borderwidth = Integer.parseInt(args[2]);
int sleeptime = Integer.parseInt(args[3]);
if (sleeptime < 0 || sleeptime > 10000) {
return false;
}
return true;
}
return false;
}
// Read the file describing the maze.
static char[][] readMazeFile(String mazefile) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(mazefile));
height = scanner.nextInt();
width = scanner.nextInt();
int arrayHeight = 2 * height + 1;
int arrayWidth = 2 * width + 1;
char[][] mazeArrays = new char[arrayHeight][arrayWidth];
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
for (int row = 0; row < arrayHeight; row++) {
for (int col = 0; col < arrayWidth; col++) {
mazeArrays[row][col] = line.charAt(col);
}
}
}
return mazeArrays;
}
// Solve the maze.
static boolean solveMaze() {
return true;
}
}
I think I have the handling of command line arguments down. The readMazeFile method is where I'm currently struggling. I just can't wrap my head around storing the maze in an array and solving it.
Thanks!
The first thing to do is to work out a data structure for you to store the maze in. I suggest using a structure that makes the solving as easy as possible, even if printing is more complicated. Here is a simple example:
class Node {
private final int row;
private final int col;
private final List<Node> paths;
}
class Maze {
private final int rowCount;
private final int colCount;
private final List<Node> nodes;
private Node start;
private Node end;
}
This, in my view, is going to be more useful than something like an array. An array would make it easy to print the maze but that's not the most difficult part of the operation. A path finding algorithm needs to be able to easily get the paths from any position which this data structure allows.
You asked for some help on reading the maze. I suggest making the reading method a static 'builder' method inside Maze. In general the structure will be something like:
class Maze {
public static Maze buildMaze(String mazeFile) {
// read row & col size from file
Maze maze = new Maze(rows, cols);
// skip first line (invariant)
for (int row = 0; row < rows; row++) {
// get next 2 lines (for horizontal & vertical paths)
for (int col = 0; col < cols; col++) {
// get corresponding horizontal wall or space
if (isHorizontalPath) {
maze.getNode(row,col).addHorizontalPath();
}
if (hasVerticalPath) {
maze.getNode(row, col).addVerticalPath();
}
// check for S and E
if (isStart) {
maze.setStart(row, col);
} else if (isEnd) {
maze.setEnd(row, col);
}
}
}
return maze;
}
}
/*
* 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.
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);
}
}
}