1
0
Fork 0

Compare commits

..

1 Commits
main ... main

Author SHA1 Message Date
Oliver Hummel ada8f538a2 Bugfix - OutofBoundsException. 2023-12-19 15:25:55 +01:00
8 changed files with 43 additions and 481 deletions

8
.idea/.gitignore vendored
View File

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -1,5 +0,0 @@
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/PR1-Spreadsheet.iml" filepath="$PROJECT_DIR$/PR1-Spreadsheet.iml" />
</modules>
</component>
</project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@ -1,7 +1,6 @@
package de.hs_mannheim.informatik.spreadsheet; package de.hs_mannheim.informatik.spreadsheet;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.Scanner;
/** /**
* Part of a simplified spreadsheet system for the PR1 programming lab at Hochschule Mannheim. * Part of a simplified spreadsheet system for the PR1 programming lab at Hochschule Mannheim.
@ -12,43 +11,19 @@ public class Axel {
public static void main(String[] args) throws FileNotFoundException { public static void main(String[] args) throws FileNotFoundException {
Spreadsheet spr = new Spreadsheet(10,10); Spreadsheet spr = new Spreadsheet(10,10);
spr.readCsv("C:/Users/kisne/IdeaProjects/PR1-Spreadsheet/tmp/test.csv", ",");
Scanner keyboard = new Scanner(System.in);
spr.put("A3", "123"); spr.put("A3", "123");
spr.put("A2", "3"); spr.put("A2", "1");
spr.put("A5", "5");
spr.put("B8", "6");
spr.put("A8", "=Summe(A5:D8)");
spr.put("J7", "=a2+2");
spr.put("J8", "=a2+J7*4");
spr.put("B9", "=41+A2");
spr.put("J5", "=7*6");
spr.put("J6", "=3/2");
System.out.println(spr); System.out.println(spr);
while(true){ spr.saveCsv("/tmp/test.csv");
System.out.print("Please enter the cell name (e.g. D8, G5): ");
String cellName = keyboard.nextLine();
System.out.print("Please enter your value or your formula (starting with '='): ");
String cellValue = keyboard.nextLine();
spr.put(cellName, cellValue);
System.out.println(spr);
System.out.print("Do you want to end the program? Y/N: ");
if(keyboard.nextLine().equalsIgnoreCase("Y")){
break;
}
}
spr.saveCsv("C:/Users/kisne/IdeaProjects/PR1-Spreadsheet/tmp/test.csv");
// TODO: You might want to put "UI loop" for entering value and formulas here resp. in some UI methods.
} }
} }

View File

@ -1,17 +1,11 @@
package de.hs_mannheim.informatik.spreadsheet; package de.hs_mannheim.informatik.spreadsheet;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* A simplified spreadsheet class for the PR1 programming lab at Hochschule Mannheim. * A simplified spreadsheet class for the PR1 programming lab at Hochschule Mannheim.
* One aspect worth mentioning is that it only supports long numbers, not doubles. * One aspect worth mentioning is that it only supports long numbers, not doubles.
@ -26,17 +20,15 @@ public class Spreadsheet {
* @param rows number of rows * @param rows number of rows
* @param cols number of columns * @param cols number of columns
*/ */
public Spreadsheet(int rows, int cols) throws IllegalArgumentException { public Spreadsheet(int rows, int cols) {
if(rows < 1 || rows > 99 || cols < 1 || cols > 26){ // TODO limit the maximum size on 99 (1..99) rows and 26 (A..Z) columns
throw new IllegalArgumentException("Range in rows 1-99; Range in cols 1-26");
}else {
cells = new Cell[rows][cols];
for (int r = 0; r < rows; r++) cells = new Cell[rows][cols];
for (int c = 0; c < cols; c++)
cells[r][c] = new Cell(); for (int r = 0; r < rows; r++)
} for (int c = 0; c < cols; c++)
cells[r][c] = new Cell();
} }
// ----- // -----
@ -70,8 +62,6 @@ public class Spreadsheet {
} }
private int getRow(String cellName) { private int getRow(String cellName) {
if(cellName.length()==3){
return Integer.parseInt(cellName.substring(1))-1;}
return cellName.charAt(1) - '1'; return cellName.charAt(1) - '1';
} }
@ -82,44 +72,18 @@ public class Spreadsheet {
* A method for reading in data from a CSV file. * A method for reading in data from a CSV file.
* @param path The file to read. * @param path The file to read.
* @param separator The char used to split up the input, e.g. a comma or a semicolon. * @param separator The char used to split up the input, e.g. a comma or a semicolon.
* @param starCellName The upper left cell where data from the CSV file should be inserted.
* @return Nothing.
* @exception IOException If path does not exist. * @exception IOException If path does not exist.
*/ */
public void readCsv(String path, String separator) throws FileNotFoundException { public void readCsv(String path, char separator, String startCellName) throws FileNotFoundException {
// TODO: implement this
ArrayList<String> lines = new ArrayList<>();
Scanner scan = new Scanner(new File(path));
while (scan.hasNextLine()) {
lines.add(scan.nextLine());
}
String[] linesArray = lines.toArray(new String[lines.size()]);
ArrayList<int[]> values = new ArrayList<>();
for(int i = 0; i < linesArray.length; i++) {
//System.out.println(linesArray[i]);
String[] zwischenSchritt = linesArray[i].split(separator);
for (int j = 0; j < zwischenSchritt.length; j++) {
System.out.println(zwischenSchritt[j]);
if(zwischenSchritt[j].startsWith("=")){
values.add(new int[]{i, j});
}else{
this.put(i, j, zwischenSchritt[j]);
}
}
for(int[] cell : values){
String[] value = linesArray[cell[0]].split(",");
String formula = value[cell[1]];
this.put(cell[0], cell[1], formula);
}
scan.close();
}
} }
/** /**
* A method for saving data to a CSV file. * A method for saving data to a CSV file.
* @param path The file to write. * @param path The file to write.
* @return Nothing.
* @exception IOException If path does not exist. * @exception IOException If path does not exist.
*/ */
public void saveCsv(String path) throws FileNotFoundException { public void saveCsv(String path) throws FileNotFoundException {
@ -143,27 +107,25 @@ public class Spreadsheet {
/** /**
* This method does the actual evaluation/calcluation of a specific cell * This method does the actual evaluation/calcluation of a specific cell
* @param row the row of the cell to be evaluated * @param cellName the name of the cell to be evaluated
* @param col the col of the cell to be evaluated * @return Nothing.
*/ */
private void evaluateCell(int row, int col) { private void evaluateCell(int row, int col) {
String formula = cells[row][col].getFormula(); String formula = cells[row][col].getFormula();
String result = ""; String result = "";
int colon = formula.indexOf(':');
String endSubstring = formula.substring((colon + 1), (formula.length()-1));
if (formula.startsWith("SUMME(")) // e.g. SUMME(A3:A8) if (formula.startsWith("SUMME(")) // e.g. SUMME(A3:A8)
result = "" + sum(formula.substring(6, colon), endSubstring); result = "" + sum(formula.substring(6, 8), formula.substring(9, 11)); // TODO adapt to cells with two digits
else if (formula.startsWith("PRODUKT(")) // e.g. PRODUKT(A3:B9) else if (formula.startsWith("PRODUKT(")) // e.g. PRODUKT(A3:B9)
result = "" + prod(formula.substring(8, colon), endSubstring); result = "TODO"; // TODO
else if (formula.startsWith("MITTELWERT(")) // e.g. MITTELWERT(A3:A5) else if (formula.startsWith("MITTELWERT(")) // e.g. MITTELWERT(A3:A5)
result = "" + mit(formula.substring(11, colon), endSubstring); result = "TODO"; // TODO
else if (formula.startsWith("STABW(")) // e.g. STABW(C6:D8) -> Standardabweichung else if (formula.startsWith("STABW(")) // e.g. STABW(C6:D8) -> Standardabweichung
result = "" + stabw(formula.substring(6, colon), endSubstring); result = "TODO"; // TODO
else if (formula.startsWith("MIN(")) // e.g. MIN(C13:H13) -> kleinster Wert else if (formula.startsWith("MIN(")) // e.g. MIN(C13:H13) -> größter Wert
result = "" + min(formula.substring(4, colon), endSubstring); result = "TODO"; // TODO
else if (formula.startsWith("MAX(")) // e.g. MAX(A1:A10) -> größter Wert else if (formula.startsWith("MAX(")) // e.g. MAX(A1:A10) -> Standardabweichung
result = "" + max(formula.substring(4, colon), endSubstring); result = "TODO"; // TODO
else if (!formula.isEmpty()) { else if (!formula.isEmpty()) {
try { try {
result = "" + calculate(formula); result = "" + calculate(formula);
@ -175,27 +137,6 @@ public class Spreadsheet {
cells[row][col].setValue("" + result); cells[row][col].setValue("" + result);
} }
/**
* Method for calculating the amount of cells with values inside a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The counted cells with values calculated.
*/
private long counterOfCellsWithValue(String startCellName, String endCellName){
long counter = 0;
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++){
for(int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A'));
if(!value.isEmpty()){
counter++;
}
}
}
return counter;
}
/** /**
* Method for calculating the sum of a rectangular block of cells, such as from A1 to B3. * Method for calculating the sum of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle. * @param startCellName The name of the cell in the upper left corner of the rectangle.
@ -203,142 +144,11 @@ public class Spreadsheet {
* @return The sum calculated. * @return The sum calculated.
*/ */
private long sum(String startCellName, String endCellName) { private long sum(String startCellName, String endCellName) {
long result = 0; // TODO implement
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++){ return 0;
for(int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A')); //"-1" because we start with 1 instead of 0. "-A" because A in ascii is 65, but we start with 0
if(!value.isEmpty()){
result += Long.parseLong(value);
}
}
}
return result;
} }
/**
* Method for calculating the product of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The product calculated.
*/
private long prod(String startCellName, String endCellName) {
long result = 0;
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++){
for(int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A'));
System.out.println(value);
if(result == 0){
result = Long.parseLong(value);
}
else if(!value.isEmpty() && !(value.equals("0"))){
result *= Long.parseLong(value);
}
}
}
return result;
}
/**
* Method for calculating the arithmetic average of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The arithmetic average calculated.
*/
private long mit(String startCellName, String endCellName) {
return sum(startCellName, endCellName)/ counterOfCellsWithValue(startCellName, endCellName);
}
/**
* Method for calculating the standard deviation of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The standard deviation calculated.
*/
private long stabw(String startCellName, String endCellName) {
long mean = mit(startCellName, endCellName);
long counter = counterOfCellsWithValue(startCellName, endCellName);
long result = 0;
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++) {
for (int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A'));
if(!value.isEmpty()){
result += (long) Math.pow(Long.parseLong(value) - mean, 2);
}
}
}
return (long) Math.sqrt(result / counter);
}
/**
* Method for finding the maximum value of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The minimum value of the block.
*/
private long min(String startCellName, String endCellName) {
long result = 0;
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++){
for(int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A')); //"-1" because we start with 1 instead of 0. "-A" because A in ascii is 65, but we start with 0
if((col == startCellName.charAt(0)) && (row == Integer.parseInt(startCellName.substring(1)))) {
result = Long.parseLong(value);
}
else if(!value.isEmpty() && (Long.parseLong(value) < result)){
result = Long.parseLong(value);
}
}
}
return result;
}
/**
* Method for finding the maximum value of a rectangular block of cells, such as from A1 to B3.
* @param startCellName The name of the cell in the upper left corner of the rectangle.
* @param endCellName The name of the cell in the lower right corner of the rectangle.
* @return The maximum value of the block.
*/
private long max(String startCellName, String endCellName) {
long result = 0;
for(char col = startCellName.charAt(0); col <= endCellName.charAt(0); col++){
for(int row = Integer.parseInt(startCellName.substring(1)); row <= Integer.parseInt(endCellName.substring(1)); row++) {
String value = get((row - 1), (col - 'A')); //"-1" because we start with 1 instead of 0. "-A" because A in ascii is 65, but we start with 0
if((col == startCellName.charAt(0)) && (row == Integer.parseInt(startCellName.substring(1)))) {
result = Long.parseLong(value);
}
else if(!value.isEmpty() && (Long.parseLong(value) > result)){
result = Long.parseLong(value);
}
}
}
return result;
}
/** /**
* This method calculates the result of a "normal" algebraic expression. It only needs to support * This method calculates the result of a "normal" algebraic expression. It only needs to support
* expressions like =B4 or =2+A3-B2, i.e. only with int numbers and other cells and with plus, * expressions like =B4 or =2+A3-B2, i.e. only with int numbers and other cells and with plus,
@ -352,47 +162,17 @@ public class Spreadsheet {
Matcher m = Pattern.compile("([A-Z][0-9]*)|[-\\+\\*/]|[0-9]*").matcher(formula); Matcher m = Pattern.compile("([A-Z][0-9]*)|[-\\+\\*/]|[0-9]*").matcher(formula);
long res = 0; long res = 0;
char operator = '+';
while (m.find()) { // TODO implement
// uncomment the following to see an example how the elements of a formula can be accessed
while (m.find()) { // m.find() must always be used before m.group()
String s = m.group(); String s = m.group();
long value; if (!s.isEmpty()) {
System.out.println(s);
if(s.isEmpty()){
continue;
}
if (!(s.matches("[-\\+\\*/]"))) {
if(s.matches("[A-Z][0-9]*")) {
int col = this.getCol(s);
int row = this.getRow(s);
value = Long.parseLong(cells[row][col].getValue());
}else{
value = Long.parseLong(s);
}
switch(operator) {
case '+':
res += value;
break;
case '-':
res -= value;
break;
case '*':
res *= value;
break;
case '/':
if (res != 0) {
res /= value;
break;
}
}
}else{
operator = s.charAt(0);
} }
} }
return res; return res;
} }

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/Axel/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/Test" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library" scope="TEST">
<library name="JUnit5.8.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.8.1/junit-jupiter-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.8.1/junit-jupiter-api-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.8.1/junit-platform-commons-1.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.8.1/junit-jupiter-params-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.8.1/junit-jupiter-engine-5.8.1.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.8.1/junit-platform-engine-1.8.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@ -1,138 +0,0 @@
package de.hs_mannheim.informatik.spreadsheet;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SpreadsheetTest {
@Test
void calculateTheSumOfNumbers(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "=13+6");
assertEquals("19", eingabe.get("T5"));
eingabe.put("T6", "=0+0");
assertEquals("0", eingabe.get("T6"));
eingabe.put("T7", "=22+34");
assertEquals("56", eingabe.get("T7"));
eingabe.put("T8", "= 9 + 3");
assertEquals("12", eingabe.get("T8"));
}
@Test
void calculateTheDifOfNumbers(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "=13-6");
assertEquals("7", eingabe.get("T5"));
eingabe.put("T6", "=0-0");
assertEquals("0", eingabe.get("T6"));
eingabe.put("T7", "=22-34");
assertEquals("-12", eingabe.get("T7"));
eingabe.put("T8", "= 9 - 3");
assertEquals("6", eingabe.get("T8"));
}
@Test
void calculateTheProdOfNumbers(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "=13*6");
assertEquals("78", eingabe.get("T5"));
eingabe.put("T6", "=0*0");
assertEquals("0", eingabe.get("T6"));
eingabe.put("T7", "=-2*34");
assertEquals("-68", eingabe.get("T7"));
eingabe.put("T8", "= 9 * 3");
assertEquals("27", eingabe.get("T8"));
}
@Test
void calculateTheValueOfQuotOfNumbers(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "=12/3");
assertEquals("4", eingabe.get("T5"));
eingabe.put("T6", "=5/0");
assertEquals("exc.", eingabe.get("T6"));
eingabe.put("T7", "= 22 / 2");
assertEquals("11", eingabe.get("T7"));
eingabe.put("T8", "= 0 / 5");
assertEquals("0", eingabe.get("T8"));
}
@Test
void calculateTheSumOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "8");
eingabe.put("T6", "2");
eingabe.put("T7", "30");
eingabe.put("T8", "10");
eingabe.put("T9", "=Summe(T5:T8)");
assertEquals("50", eingabe.get("T9"));
}
void calculateTheSProdOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "2");
eingabe.put("T6", "4");
eingabe.put("T7", "6");
eingabe.put("T8", "10");
eingabe.put("T9", "=Produkt(T5:T8)");
assertEquals("480", eingabe.get("T9"));
}
void calculateTheMitOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "8");
eingabe.put("T6", "2");
eingabe.put("T7", "30");
eingabe.put("T8", "10");
eingabe.put("T9", "=Mittelwert(T5:T8)");
assertEquals("12", eingabe.get("T9"));
}
void calculateTheStabwOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "8");
eingabe.put("T6", "2");
eingabe.put("T7", "30");
eingabe.put("T8", "10");
eingabe.put("T9", "=Stabw(T5:T8)");
assertEquals("12", eingabe.get("T9"));
}
void calculateTheMinOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "8");
eingabe.put("T6", "2");
eingabe.put("T7", "30");
eingabe.put("T8", "10");
eingabe.put("T9", "=min(T5:T8)");
assertEquals("2", eingabe.get("T9"));
}
void calculateTheMaxOfRectangular(){
Spreadsheet eingabe = new Spreadsheet(99, 26);
eingabe.put("T5", "8");
eingabe.put("T6", "2");
eingabe.put("T7", "30");
eingabe.put("T8", "10");
eingabe.put("T9", "=Summe(T5:T8)");
assertEquals("30", eingabe.get("T9"));
}
}