So for this program, the mean and median are supposed to calculated and displayed but I do not think the data I am inputting is getting put into the array because it runs without error but does not display any data I have put into it.
public static double Mean(double[] gradeArray, int numGrades) {
double totalArray = 0.0;
double mean;
for (int i = 0; i < numGrades; i++) {
totalArray = gradeArray[i] + totalArray;
}
mean = totalArray / numGrades;
return mean;
}
public static double Median(double[] gradeArray, int numGrades) {
double median;
Arrays.sort(gradeArray, 0, numGrades);
if (numGrades % 2 == 0) {
median = ((gradeArray[(numGrades / 2)] + gradeArray[(numGrades / 2 + 1)]) / 2);
} else {
median = gradeArray[(numGrades / 2)];
}
return median;
}
private void Enter_Grades_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
double[] totalArray = new double[25];
String text_box_input_str = null;
double text_box_input_num = 0;
int numGrades = 0;
String num_grades_str;
DecimalFormat df = new DecimalFormat("#0.0##");
do {
try {
text_box_input_str = JOptionPane.showInputDialog(null, "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
if (text_box_input_str == null || text_box_input_str.isEmpty()) {
return;
}
if (text_box_input_num > 0) {
double[] gradeArray = null;
gradeArray[numGrades] = text_box_input_num;
numGrades++;
num_grades_str = Integer.toString(numGrades);
num_grades_text.setText(num_grades_str);
Mean_Text.setText(df.format(Mean(gradeArray, numGrades)));
Median_Text.setText(df.format(Median(gradeArray, numGrades)));
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught");
JOptionPane.showMessageDialog(null, "You Must Input numeric data!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
}
} while (text_box_input_str != null && !text_box_input_str.isEmpty());
}
I expect the program to calculate the data that is inputted and calculate the mean and median and then display the totals
it looks like text_box_input_num is set to 0, never updated, but then there is an if check if it's > 0
Rather than pointing out the problem with your code directly, I'll give some pointers on how to find it yourself.
break your code down into smaller parts
for each part, write both the method and the tests that prove the method does what you expect
once the individual parts are working, write the method (and tests) that use them.
You'll end up with several methods with names like getValues, hasValue, printError, checkValidValue, showMedian etc. all of which do exactly what you want.
I guarantee that if you do that it'll become pretty clear very quickly what's wrong.
Related
I've just started learning java since last week. I'm using book called 'head first java' and i'm struggling with solving problems about ArrayList. Error says "The method setLocationCells(ArrayList) in the type DotCom is not applicable for the
arguments (int[])" and I haven't found the solution :( help me..!
enter image description here
This looks like a Locate & Conquer type game similar to the game named Battleship with the exception that this game is a single player game played with a single hidden ship in a single horizontal row of columnar characters. Rather simplistic but kind of fun to play I suppose. The hard part is to locate the hidden ship but once you've located it, conquering (sinking) it becomes relatively easy. I'm sure this isn't the games' intent since it is after all named "The Dot Com Game" but the analogy could be possibly helpful.
There are several issues with your code but there are two major ones that just can not be there for the game to work:
Issue #1: The call to the DotCom.setLocationCells() method:
The initial problem is located within the DotComGame class on code line 13 (as the Exception indicates) where the call is made to the DotCom.setLocationCells() method. As already mentioned in comments the wrong parameter type is passed to this method. You can not pass an int[] Array to the setLocationCell() method when this method contains a parameter signature that stipulates it requires an ArrayList object. The best solution in my opinion would be to satisfy the setLocationCells() method parameter requirement...supply an ArrayList to this method.
The reason I say this is because all methods within the DotCom class work with an established ArrayList and one of the tasks of one of these methods (the checkYourself() method) actually removes elements from the ArrayList which is easy to do from a collection but very cumbersome to do the same from an Array.
To fix this problem you will need to change the data type for the locations variable located within the DotComGame class. Instead of using:
int[] locations = {randomNum, randomNum + 1, randomNum + 2};
you should have:
ArrayList<Integer> locations = new ArrayList<>(
Arrays.asList(random, randomNum + 1, randomNum + 2));
or you could do it this way:
ArrayList<Integer> locations = new ArrayList<>();
locations.add(randomNum);
locations.add(randomNum + 1);
locations.add(randomNum + 2);
There are other ways but these will do for now. Now, when the call to the setLocationCells() method is made you ahouldn't get an exception this issue should now be resolved.
Issue #2: The call to the DotCom.checkYourself() method:
Again, this particular issue is located within the DotComGame class on code line 18 where the call is made to the DotCom.checkYourself() method. Yet another parameter data type mismatch. You are trying to pass a variable of type String (named guess) to this method whereas its signature stipulates that it requires an integer (int) value. That again is a no go.
To fix this problem you will need to convert the string numerical value held by the guess variable to an Integer (int) value. So instead of having this:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
String result = theDotCom.checkYourself(guess);
// ... The rest of your while loop code ...
}
you should have something like:
while(isAlive) {
String guess = helper.getUserInput("Enter a Number: ");
/* Validate. Ensure guess holds a string representation
of a Integer numerical value. */
if (!guess.matches("\\d+")) {
System.err.println("Invalid Value (" + guess
+ ") Supplied! Try again...");
continue;
}
int guessNum = Integer.parseInt(guess);
String result = theDotCom.checkYourself(guessNum);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println(numOfGuesses + " guesses!");
}
else if (result.equals("hit")) {
// Do Something If You Like
System.out.println("HIT!");
}
else {
System.out.println("Missed!");
}
}
Below is a game named Simple Battleship which I based off of your code images (please don't use images for code anymore - I hate using online OCR's ;)
BattleshipGame.java - The application start class:
import java.awt.Toolkit;
public class BattleshipGame {
public static int gameLineLength = 10;
public static void main(String[] args) {
GameHelper helper = new GameHelper();
Battleship theDotCom = new Battleship();
int score = 0; // For keeping an overall score
// Display About the game...
System.out.println("Simple Battleship Game");
System.out.println("======================");
System.out.println("In this game you will be displayed a line of dashes.");
System.out.println("Each dash has the potential to hide a section of a");
System.out.println("hidden Battleship. The size of this ship is randomly");
System.out.println("chosen by the game engine and can be from 1 to 5 sections");
System.out.println("(characters) in length. The score for each battle is based");
System.out.println("on the length of the game line that will be displayed to");
System.out.println("you (default is a minimum of 10 charaters). You now have");
System.out.println("the option to supply the game line length you want to play");
System.out.println("with. If you want to use the default then just hit ENTER:");
System.out.println();
// Get the desire game line length
String length = helper.getUserInput("Desired Game Line Length: --> ", "Integer", true, 10, 10000);
if (!length.isEmpty()) {
gameLineLength = Integer.parseInt(length);
}
System.out.println();
// Loop to allow for continuous play...
boolean alwaysReplay = true;
while (alwaysReplay) {
int numOfGuesses = 0;
/* Create a random ship size to hide within the line.
It could be a size from 1 to 5 characters in length. */
int shipSize = new java.util.Random().nextInt((5 - 1) + 1) + 1;
int randomNum = (int) (Math.random() * (gameLineLength - (shipSize - 1)));
int[] locations = new int[shipSize];
for (int i = 0; i < locations.length; i++) {
locations[i] = randomNum + i;
}
System.out.println("Destroy the " + shipSize + " character ship hidden in the");
System.out.println("displayed line below:");
System.out.println();
String gameLine = String.join("", java.util.Collections.nCopies(gameLineLength, "-"));
theDotCom.setLocationCells(locations);
// Play current round...
boolean isAlive = true;
while (isAlive == true) {
System.out.println(gameLine);
String guess = helper.getUserInput("Enter a number from 1 to " + gameLineLength
+ " (0 to quit): --> ", "Integer", 1, gameLineLength);
int idx = Integer.parseInt(guess);
if (idx == 0) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
alwaysReplay = false;
break;
}
idx = idx - 1;
String result = theDotCom.checkYourself(idx);
numOfGuesses++;
System.out.println(result);
if (result.equalsIgnoreCase("kill")) {
Toolkit.getDefaultToolkit().beep();
isAlive = false;
/* Tally the score dependent upon the gameLineLength... */
if (gameLineLength <= 10) { score += 5; }
else if (gameLineLength > 10 && gameLineLength <= 20) { score += 10; }
else if (gameLineLength > 20 && gameLineLength <= 30) { score += 15; }
else if (gameLineLength > 30 && gameLineLength <= 40) { score += 20; }
else { score += 25; }
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
System.out.println(gameLine);
System.out.println(numOfGuesses + " guesses were made to sink the hidden ship.");
System.out.println("Your overall score is: " + (score < 0 ? 0 : score));
}
else if (result.equalsIgnoreCase("hit")) {
gameLine = gameLine.substring(0, idx) + "x" + gameLine.substring(idx + 1);
}
if (result.equalsIgnoreCase("miss")) {
score -= 1;
}
System.out.println();
}
// Play Again? [but only if 'alwaysReplay' holds true]
if (alwaysReplay) {
String res = helper.getAnything("<< Press ENTER to play again >>\n"
+ "<< or enter 'q' to quit >>");
if (res.equalsIgnoreCase("q")) {
System.out.println("Quiting with an overall score of: " + score + " ... Bye-Bye");
break;
}
System.out.println();
}
}
}
}
GameHelper.java - The GameHelper class:
import java.util.Scanner;
public class GameHelper {
private final Scanner in = new Scanner(System.in);
public String getUserInput(String prompt, String responseType, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getUserInput(String prompt, String responseType, boolean allowNothing, int... minMAX) {
int min = 0, max = 0;
if (minMAX.length == 2) {
min = minMAX[0];
max = minMAX[1];
}
if (minMAX.length > 0 && min < 1 || max < 1) {
throw new IllegalArgumentException("\n\ngetUserInput() Method Error! "
+ "The optional parameters 'min' and or 'max' can not be 0!\n\n");
}
String response = "";
while (response.isEmpty()) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
response = in.nextLine().trim();
if (response.isEmpty() && allowNothing) {
return "";
}
if (responseType.matches("(?i)\\b(int|integer|float|double)\\b")) {
if (!response.matches("-?\\d+(\\.\\d+)?") ||
(responseType.toLowerCase().startsWith("int") && response.contains("."))) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
continue;
}
}
// Check entry range value if the entry is to be an Integer
if (responseType.toLowerCase().startsWith("int")) {
int i = Integer.parseInt(response);
if (i != 0 && (i < min || i > max)) {
System.err.println("Invalid Entry (" + response + ")! Try again...");
response = "";
}
}
}
return response;
}
public String getAnything(String prompt) {
if (prompt.trim().endsWith("-->")) {
System.out.print(prompt);
}
else {
System.out.println(prompt);
}
return in.nextLine().trim();
}
}
Battleship.java - The Battleship class:
import java.util.ArrayList;
public class Battleship {
private ArrayList<Integer> locationCells;
public void setLocationCells(java.util.ArrayList<Integer> loc) {
locationCells = loc;
}
// Overload Method (Java8+)
public void setLocationCells(int[] loc) {
locationCells = java.util.stream.IntStream.of(loc)
.boxed()
.collect(java.util.stream.Collectors
.toCollection(java.util.ArrayList::new));
}
/*
// Overload Method (Before Java8)
public void setLocationCells(int[] loc) {
// Clear the ArrayList in case it was previously loaded.
locationCells.clear();
// Fill the ArrayList with integer elements from the loc int[] Array
for (int i = 0; i < loc.length; i++) {
locationCells.add(loc[i]);
}
}
*/
/**
* Completely removes one supplied Integer value from all elements
* within the supplied Integer Array if it exist.<br><br>
*
* <b>Example Usage:</b><pre>
*
* {#code int[] a = {103, 104, 100, 10023, 10, 140, 2065};
* a = removeFromArray(a, 104);
* System.out.println(Arrays.toString(a);
*
* // Output will be: [103, 100, 10023, 10, 140, 2065]}</pre>
*
* #param srcArray (Integer Array) The Integer Array to remove elemental
* Integers from.<br>
*
* #param intToDelete (int) The Integer to remove from elements within the
* supplied Integer Array.<br>
*
* #return A Integer Array with the desired elemental Integers removed.
*/
public static int[] removeFromArray(int[] srcArray, int intToDelete) {
int[] arr = {};
int cnt = 0;
boolean deleteIt = false;
for (int i = 0; i < srcArray.length; i++) {
if (srcArray[i] != intToDelete) {
arr[cnt] = srcArray[i];
cnt++;
}
}
return arr;
}
public String checkYourself(int userInput) {
String result = "MISS";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "KILL";
}
else {
result = "HIT";
}
}
return result;
}
}
I am trying to write a program that will receive a function as a String and solve it. For ex. "5*5+2/2-8+5*5-2" should return 41
I wrote the code for multiplication and divisions and it works perfectly:
public class Solver
{
public static void operationS(String m)
{
ArrayList<String> z = new ArrayList<String>();
char e= ' ';
String x= " ";
for (int i =0; i<m.length();i++)
{
e= m.charAt(i);
x= Character.toString(e);
z.add(x);
}
for (int i =0; i<z.size();i++)
{
System.out.print(z.get(i));
}
other(z);
}
public static void other(ArrayList<String> j)
{
int n1=0;
int n2=0;
int f=0;
String n= " ";
for (int m=0; m<j.size();m++)
{
if ((j.get(m)).equals("*"))
{
n1 = Integer.parseInt(j.get(m-1));
n2 = Integer.parseInt(j.get(m+1));
f= n1*n2;
n = Integer.toString(f);
j.set(m,n);
j.remove(m+1);
j.remove(m-1);
m=0;
}
for (int e=0; e<j.size();e++)
{
if ((j.get(e)).equals("/"))
{
n1 = Integer.parseInt(j.get(e-1));
n2 = Integer.parseInt(j.get(e+1));
f= n1/n2;
n = Integer.toString(f);
j.set(e,n);
j.remove(e+1);
j.remove(e-1);
e=0;
}
}
}
System.out.println();
for (int i1 =0; i1<j.size();i1++)
{
System.out.print(j.get(i1)+",");
}
However, for adding and subtracting, since there isnt an order for adding and subtracting, just whichever comes first, I wrote the following:
int x1=0;
int x2=0;
int x3=0;
String z = " ";
for (int g=0; g<j.size();g++)
{
if ((j.get(g)).equals("+"))
{
x1= Integer.parseInt(j.get(g-1));
x2= Integer.parseInt(j.get(g+1));
x3= x1+x2;
z = Integer.toString(x3);
j.set(g,z);
j.remove(g+1);
j.remove(g-1);
g=0;
}
g=0;
if ((j.get(g)).equals("-"))
{
x1= Integer.parseInt(j.get(g-1));
x2= Integer.parseInt(j.get(g+1));
x3= x1-x2;
z = Integer.toString(x3);
j.set(g,z);
j.remove(g+1);
j.remove(g-1);
g=0;
}
g=0;
}
System.out.println();
for (int i1 =0; i1<j.size();i1++)
{
System.out.print(j.get(i1)+",");
}
After this, it prints:
25,+,1,-,8,+,25,–,2,
. What am I doing wrong? Multiplication and dividing seem to be working perfectly
You have 2 problems:
1) g=0; statements after if and else blocks will make you go into an infinite loop.
2) From the output you gave, the first minus (-) is Unicode character HYPHEN-MINUS (U+002D), while the second minus (–) is Unicode character EN DASH (U+2013), so (j.get(g)).equals("-") fails for the second minus as they are not equal.
Going for an answer that doesn't help with your exact specific problem, but that hopefully helps you much further than that.
On a first glance, there are various problems with your code:
Your are using super-short variable names all over the place. That saves you maybe 1 minute of typing overall; and costs you 5, 10, x minutes every time you read your code; or show it to other people. So: dont do that. Use names that say what the thing behind that name is about.
You are using a lot of low-level code. You use a "couting-for" loop to iterate a list (called j, that is really really horrible!) for example. Meaning: you make your code much more complicated to read than it ought to be.
In that way, it looks like nobody told you so far, but the idea of code is: it should be easy to read and understand. Probably you dont get grades for that, but believe me: in the long run, learning to write readable code is a super-important skill. If that got you curious, see if you can get a hand on "Clean code" by Robert Martin. And study that book. Then study it again. And again.
But the real problem is your approach to solve this problem. As I assume: this is some part of study assignment. And the next step will be that you don't have simple expressions such as "1+2*3"; but that you are asked to deal with something like "sqrt(2) + 3" and so on. Then you will be asked to add variables, etc. And then your whole approach breaks apart. Because your simple string operations won't do it any more.
In that sense: you should look into this question, and carefully study the 2nd answer by Boann to understand how to create a parser that dissects your input string into expressions that are then evaluated. Your code does both things "together"; thus making it super-hard to enhance the provided functionality.
You can use the built-in Javascript engine
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String code = "5*5+2/2-8+5*5-2";
System.out.println(engine.eval(code));
}
Primarily Don't Repeat Yourself (the DRY principle). And use abstractions (full names, extracting methods when sensible). Static methods are a bit cumbersome, when using several methods. Here it is handy to use separate methods.
Maybe you want something like:
Solver solver = new Solver();
List<String> expr = solver.expression("5*5+2/2-8+5*5-2");
String result = solver.solve(expr);
A more abstract Solver class would do:
class Solver {
List<String> expression(String expr) {
String[] args = expr.split("\\b");
List<String> result = new ArrayList<>();
Collections.addAll(result, args);
return result;
}
String solve(List<String> args) {
solveBinaryOps(args, "[*/]");
solveBinaryOps(args, "[-+]");
return args.stream().collect(Collectors.joining(""));
}
The above solveBinaryOps receives a regular expression pattern or alternatively simply in some form the operators you want to tackle.
It takes care of operator precedence.
private void solveBinaryOps(List<String> args, String opPattern) {
for (int i = 1; i + 1 < args.length; ++i) {
if (args.get(i).matches(opPattern)) {
String value = evalBinaryOp(args.get(i - 1), args.get(i), args.get(i + 1));
args.set(i, value);
args.remove(i + 1);
args.remove(i - 1);
--i; // Continue from here.
}
}
}
private String evalBinaryOp(String lhs, String op, String rhs) {
int x = Integer.parseInt(lhs);
int y = Integer.parseInt(rhs);
int z = 0;
switch (op) {
case "*":
z = x * y;
break;
case "/":
z = x / y;
break;
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
return Integer.toString(z);
}
}
The above can be improved at several points. But it is readable, and rewritable.
public class Solver {
public static void main(String args[]) {
operation("5+2*5-6/2+1+5*12/3");
}
public static void operation(String m) {
ArrayList<Object> expressions = new ArrayList<Object>();
String e;
String x = "";
for (int i = 0; i < m.length(); i++) {
e = m.substring(i, i + 1);
if (!(e.equals("*") || e.equals("/") || e.equals("+") || e
.equals("-"))) {
x += e;
continue;
} else {
if (!x.equals("") && x.matches("[0-9]+")) {
int oper = Integer.parseInt(x);
expressions.add(oper);
expressions.add(m.charAt(i));
x = "";
}
}
}
if (!x.equals("") && x.matches("[0-9]+")) {
int oper = Integer.parseInt(x);
expressions.add(oper);
x = "";
}
for (int i = 0; i < expressions.size(); i++) {
System.out.println(expressions.get(i));
}
evaluateExpression(expressions);
}
public static void evaluateExpression(ArrayList<Object> exp) {
//Considering priorities we calculate * and / first and put them in a list mulDivList
ArrayList<Object> mulDivList=new ArrayList<Object>();
for (int i = 0; i < exp.size(); i++) {
if (exp.get(i) instanceof Character) {
if ((exp.get(i)).equals('*')) {
int tempRes = (int) exp.get(i - 1) * (int) exp.get(i + 1);
exp.set(i - 1, null);
exp.set(i, null);
exp.set(i + 1, tempRes);
}
else if ((exp.get(i)).equals('/')) {
int tempRes = (int) exp.get(i - 1) / (int) exp.get(i + 1);
exp.set(i - 1, null);
exp.set(i, null);
exp.set(i + 1, tempRes);
}
}
}
//Create new list with only + and - operations
for(int i=0;i<exp.size();i++)
{
if(exp.get(i)!=null)
mulDivList.add(exp.get(i));
}
//Calculate + and - .
for(int i=0;i<mulDivList.size();i++)
{
if ((mulDivList.get(i)).equals('+')) {
int tempRes = (int) mulDivList.get(i - 1) + (int) mulDivList.get(i + 1);
mulDivList.set(i - 1, null);
mulDivList.set(i, null);
mulDivList.set(i + 1, tempRes);
}
else if ((mulDivList.get(i)).equals('-')) {
int tempRes = (int) mulDivList.get(i - 1) - (int) mulDivList.get(i + 1);
mulDivList.set(i - 1, null);
mulDivList.set(i, null);
mulDivList.set(i + 1, tempRes);
}
}
System.out.println("Result is : " + mulDivList.get(mulDivList.size() - 1));
}
}
Having a String representation of a number(no decimals), what's the best way to convert it to either one of java.lang.Integer or java.lang.Long or java.math.BigInteger? The only condition is that the converted type should be of minimal datatype required to hold the number.
I've this current implementation that works fine, but I would like to know if there's a better code without exception handling.
package com.stackoverflow.programmer;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
String number = "-12121111111111111";
Number numberObject = null;
try {
numberObject = Integer.valueOf(number);
} catch (NumberFormatException nfe) {
System.out.println("Number will not fit into Integer type. Trying Long...");
try {
numberObject = Long.valueOf(number);
} catch (NumberFormatException nfeb) {
System.out.println("Number will not fit into Long type. Trying BigInteger...");
numberObject = new BigInteger(number);
}
}
System.out.println(numberObject.getClass() + " : "
+ numberObject.toString());
}
}
From what you said, here is what I would have done:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
public class TestSO09_39463168_StringToMinimalNumber {
public static void main(String[] args) {
List<String> strNumbers = Arrays.asList("0", //int
"123", //int
"-456", //int
"2147483700", // Long
"-2147483700", // Long
"9223372036854775900", //BigInt
"-9223372036854775900" //BigInt
);
for(String strNumber : strNumbers){
Number number = stringToMinimalNumber(strNumber);
System.out.println("The string '"+strNumber+"' is a "+number.getClass());
}
}
public static Number stringToMinimalNumber(String s){
BigInteger tempNumber = new BigInteger(s);
if(tempNumber.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || tempNumber.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0){
return tempNumber;
} else if(tempNumber.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0 || tempNumber.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0){
return tempNumber.longValue(); //Autobox to Long
} else {
return tempNumber.intValue(); //Autobox to Integer
}
}
}
You must use a temporary BigInteger, or else you'll end up with lazarov's solution, which is correct, but you can't really do something like that for reason mentionned in the comments.
Anyway, every BigInteger (the ones that are not returned) will be garbage collected. As for autoboxing, I don't think it's that of a bad thing. You could also make "BigInteger.valueOf(Long.MAX_VALUE))" as a constant. Maybe the compiler or the JVM will do this on its own.
I'm not really sure of how efficient it is, and using only BigInteger might be a good idea (as Spotted did), because I serioulsy doubt it would really improve the rest of your code to use the right size, and it might even be error prone if you try to use these Numbers with each other ... But again, it all depend on what you need. (and yes, using Exception as flow control is a really bad idea, but you can add a try catch on the BigInteger tempNumber = new BigInteger(s); to throw your own exception if s is not a number at all)
For recreational purpose, I have made the solution without using a BigInteger, and only with String parsing (this is still not what I recommand to do, but it was fun :)
public static final String INT_MAX_VALUE = "2147483647";
public static final String LONG_MAX_VALUE = "9223372036854775807";
public static Number stringToMinimalNumberWithoutBigInteger(String numberStr){
//Removing the minus sign to test the value
String s = (numberStr.startsWith("-") ? numberStr.substring(1,numberStr.length()) : numberStr);
if(compareStringNumber(s, LONG_MAX_VALUE) > 0){
return new BigInteger(numberStr);
} else if(compareStringNumber(s, INT_MAX_VALUE) > 0){
return new Long(numberStr);
} else {
return new Integer(numberStr);
}
}
//return postive if a > b, negative if a < b, 0 if equals;
private static int compareStringNumber(String a, String b){
if(a.length() != b.length()){
return a.length() - b.length();
}
for(int i = 0; i < a.length(); i++){
if( a.codePointAt(i) != b.codePointAt(i) ){ //Or charAt()
return a.codePointAt(i) - b.codePointAt(i);
}
}
return 0;
}
Please don't use exceptions for handling flow control, this is a serious anti-pattern (also here).
As you mentionned in the comments, the real thing you've been asked is to convert a List<String> into a List<Number>.
Also, if I understand correctly, you know that:
You should encounter only numbers without decimals
The biggest value you can encounter is possibly unbound
Based on that, the following method will do the job in a more clever way:
private static List<Number> toNumbers(List<String> strings) {
return strings.stream()
.map(BigInteger::new)
.collect(Collectors.toList());
}
Eidt: if you're not very familiar with the stream concept, here's the equivalent code without streams:
private static List<Number> toNumbers(List<String> strings) {
List<Number> numbers = new ArrayList<>();
for (String s : strings) {
numbers.add(new BigInteger(s));
}
return numbers;
}
Well if you want to do it "by hand" try something like this:
We define the max values as strings :
String intMax = "2147483647";
String longMax = "9223372036854775807";
and our number:
String ourNumber = "1234567890"
Now our logic will be simple :
We will check lenghts of strings firstly
If our numbers length < int max length : IT IS INT
If our numbers length == int max length : Check is it INT or LONG
If our numbers length > int max length :
3.1 If our numbers length < long max length : IT IS LONG
3.2 If our numbers length == long max length : Check is it LONG or BIG INTEGER
3.3 If our numbers length > long max length : IT IS BIG INTEGER
The code should look something like this (I have not tried to compile it may have syntax or other errors) :
if(ourNumber.lenght() < intMax.length ){
System.out.println("It is an Integer");
} else if(ourNumber.lenght() == intMax.length){
// it can be int if the number is between 2000000000 and 2147483647
char[] ourNumberToCharArray = ourNumber.toCharArray();
char[] intMaxToCharArray = intMax.toCharArray();
int diff = 0;
for(int i = 0; i < ourNumberToCharArray.length; i++) {
diff = Character.getNumericValue(intMaxToCharArray[i]) - Character.getNumericValue(ourNumberToCharArray[i]);
if(diff > 0) {
System.out.println("It is a Long");
break;
} else if(diff < 0) {
System.out.println("It is an Integer");
break;
}
}
if(diff == 0){
System.out.println("It is an Integer");
}
} else {
if(ourNumber.lenght() < longMax.length()) {
System.out.println("It is a Long");
} else if(ourNumber.lenght() == longMax.length()){
char[] ourNumberToCharArray = ourNumber.toCharArray();
char[] longMaxToCharArray = longMax.toCharArray();
int diff = 0;
for(int i = 0; i < ourNumberToCharArray.length; i++) {
diff = Character.getNumericValue(longMaxToCharArray[i]) - Character.getNumericValue(ourNumberToCharArray[i]);
if(diff > 0) {
System.out.println("It is a BigInteger");
break;
} else if(diff < 0) {
System.out.println("It is a Long");
break;
}
}
if(diff == 0){
System.out.println("It is a Long");
}
} else {
System.out.println("It is a BigInteger");
}
}
Then logic that checks if the numbers match or not is the same in both cases you can but it in a function for example.
I am new to Java and am still getting used to the minor difference so please excuse any mistakes you may find ridiculous.
I am trying to write a program that stores temperature and can be used to call that temperature in Celsius or in Fahrenheit. My only issue comes with the command line arguments, after successfully compiling my program I enter the following:
java Driver 0.0C 32.0F
And then I get this:
Exception in thread "main" java.lang.NumberFormatException: For input string:
"0.0C"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Float.parseFloat(Float.java:452)
at Driver.main(Driver.java:47)
My program is still not completely polished up so I know that the getters can be written to be much for efficient and that the driver program doesn't even call the temperature class, but this is not my concern at the moment. My Driver is supposed to take in the input and determine from the 'C' or 'F' character whether the value is in Celsius or Fahrenheit. It then parses the string and truncates the C or F and stores the values contained in the strings as floats. I am using Eclipse and the program is object oriented, this is my code:
public class Temperature {
private float temperature;
private char scale;
// default constructor
Temperature() {
this.temperature = 0;
this.scale = 'C';
}
Temperature(float temperatureIn) {
this.temperature = temperatureIn;
this.scale = 'C';
}
Temperature(char scaleIn) {
this.temperature = 0;
this.scale = scaleIn;
}
Temperature(float temperatureIn, char scaleIn) {
this.temperature = temperatureIn;
this.scale = scaleIn;
}
float degreesC(float degreesF) {
float degreesC = (5 * (degreesF - 32)) / 9;
return degreesC;
}
float degreesF(float degreesC) {
float degreesF = (9*(degreesC / 5)) + 32;
return degreesF;
}
void setTemperature(float temperatureIn) {
temperature = temperatureIn;
}
void setScale(char scaleIn) {
scale = scaleIn;
}
void setBothValues(float temperatureIn, char scaleIn) {
temperature = temperatureIn;
scale = scaleIn;
}
int compareTemps(Temperature temp1, Temperature temp2) {
// both values will be compared in Farenheit
Temperature temp1temp = temp1;
if (temp1temp.scale == 'C') {
temp1temp.temperature = degreesF(temp1temp.temperature);
temp1temp.scale = 'F';
}
Temperature temp2temp = temp2;
if (temp2temp.scale == 'C') {
temp2temp.temperature = degreesF(temp2temp.temperature);
temp2temp.scale = 'F';
}
if (temp1temp.temperature == temp2temp.temperature) {
return 0;
}
if (temp1temp.temperature > temp2temp.temperature)
return 1;
if (temp1temp.temperature < temp2temp.temperature)
return -1;
return 0;
}
}
And the main driver program:
public class Driver {
public static void main(String[] args) {
// ints to hold the temperature values
float temp1Value = 0;
float temp2Value = 0;
// strings to hold the scale types
char temp1Scale = 'C';
char temp2Scale = 'C';
// declare objects of type temperature
Temperature firstTemp = null;
Temperature secondTemp = null;
// copy scale values of temperatures
int scaleIndex = 0;
int scaleIndex2 = 0;
if (args.length > 0) {
if (args[0].indexOf('C') != -1)
{
scaleIndex = args[0].indexOf('C');
temp1Scale = args[0].charAt(scaleIndex);
}
else if (args[0].indexOf('F') != -1)
{
scaleIndex = args[0].indexOf('F');
temp1Scale = args[0].charAt(scaleIndex);
}
if (args[1].indexOf('C') != -1)
{
scaleIndex = args[1].indexOf('C');
temp2Scale = args[1].charAt(scaleIndex2);
}
else if (args[1].indexOf('F') != -1)
{
scaleIndex = args[1].indexOf('F');
temp2Scale = args[1].charAt(scaleIndex2);
}
}
// parse the values to exclude scales and copy to strings holding temperature values
if (args.length > 0) {
temp1Value = Float.parseFloat(args[0].substring(0, scaleIndex));
temp2Value = Float.parseFloat(args[1].substring(0, scaleIndex2));
}
}
}
the exception you are getting is beacuse you passed '0.0C' to the float parser at:
tempValue = Float.parseFloat(args[1].substring(0, scaleIndex));
that is beacuse you do
scaleIndex = args[1].indexOf('F');
effectively overwriting the scaleIndex instead of setting scaleIndex2
please be open minded with my following recommendations:
object oriented means you create classes which will take up responsibility
your Temperature class stores temp in celsius and in fahrenheit too..which might be easier, but storing only for example Kelvins would mean you have a strong inner concept inside the class
when someone asks for C or F it calculates from the K
after that the Temperature class's constructor should be responsible for parsing '0.0C' and '42.0F'
It is better you take inputs as <temp1> <unit1> <temp2> <unit2>. This way you'll get all the parameter you need in the desired format. You can now parse args[0] and args[2] for tempValues and the other two parameter for the units. Even better, just take <temp1> <temp2> as you command line arguments and decide that <temp1> is in degC and <temp2> is in F.
I have an algorithm that recursively makes change in the following manner:
public static int makeChange(int amount, int currentCoin) {
//if amount = zero, we are at the bottom of a successful recursion
if (amount == 0){
//return 1 to add this successful solution
return 1;
//check to see if we went too far
}else if(amount < 0){
//don't count this try if we went too far
return 0;
//if we have exhausted our list of coin values
}else if(currentCoin < 0){
return 0;
}else{
int firstWay = makeChange(amount, currentCoin-1);
int secondWay = makeChange(amount - availableCoins[currentCoin], currentCoin);
return firstWay + secondWay;
}
}
However, I'd like to add the capability to store or print each combination as they successfully return. I'm having a bit of a hard time wrapping my head around how to do this. The original algorithm was pretty easy, but now I am frustrated. Any suggestions?
CB
Without getting into the specifics of your code, one pattern is to carry a mutable container for your results in the arguments
public static int makeChange(int amount, int currentCoin, List<Integer>results) {
// ....
if (valid_result) {
results.add(result);
makeChange(...);
}
// ....
}
And call the function like this
List<Integer> results = new LinkedList<Integer>();
makeChange(amount, currentCoin, results);
// after makeChange has executed your results are saved in the variable "results"
I don't understand logic or purpose of above code but this is how you can have each combination stored and then printed.
public class MakeChange {
private static int[] availableCoins = {
1, 2, 5, 10, 20, 25, 50, 100 };
public static void main(String[] args) {
Collection<CombinationResult> results = makeChange(5, 7);
for (CombinationResult r : results) {
System.out.println(
"firstWay=" + r.getFirstWay() + " : secondWay="
+ r.getSecondWay() + " --- Sum=" + r.getSum());
}
}
public static class CombinationResult {
int firstWay;
int secondWay;
CombinationResult(int firstWay, int secondWay) {
this.firstWay = firstWay;
this.secondWay = secondWay;
}
public int getFirstWay() {
return this.firstWay;
}
public int getSecondWay() {
return this.secondWay;
}
public int getSum() {
return this.firstWay + this.secondWay;
}
public boolean equals(Object o) {
boolean flag = false;
if (o instanceof CombinationResult) {
CombinationResult r = (CombinationResult) o;
flag = this.firstWay == r.firstWay
&& this.secondWay == r.secondWay;
}
return flag;
}
public int hashCode() {
return this.firstWay + this.secondWay;
}
}
public static Collection<CombinationResult> makeChange(
int amount, int currentCoin) {
Collection<CombinationResult> results =
new ArrayList<CombinationResult>();
makeChange(amount, currentCoin, results);
return results;
}
public static int makeChange(int amount, int currentCoin,
Collection<CombinationResult> results) {
// if amount = zero, we are at the bottom of a successful recursion
if (amount == 0) {
// return 1 to add this successful solution
return 1;
// check to see if we went too far
} else if (amount < 0) {
// don't count this try if we went too far
return 0;
// if we have exhausted our list of coin values
} else if (currentCoin < 0) {
return 0;
} else {
int firstWay = makeChange(
amount, currentCoin - 1, results);
int secondWay = makeChange(
amount - availableCoins[currentCoin],
currentCoin, results);
CombinationResult resultEntry = new CombinationResult(
firstWay, secondWay);
results.add(resultEntry);
return firstWay + secondWay;
}
}
}
I used the following:
/**
* This is a recursive method that calculates and displays the combinations of the coins included in
* coinAmounts that sum to amountToBeChanged.
*
* #param coinsUsed is a list of each coin used so far in the total. If this branch is successful, we will add another coin on it.
* #param largestCoinUsed is used in the recursion to indicate at which coin we should start trying to add additional ones.
* #param amountSoFar is used in the recursion to indicate what sum we are currently at.
* #param amountToChange is the original amount that we are making change for.
* #return the number of successful attempts that this branch has calculated.
*/private static int change(List<Integer> coinsUsed, Integer currentCoin, Integer amountSoFar, Integer amountToChange)
{
//if last added coin took us to the correct sum, we have a winner!
if (amountSoFar == amountToChange)
{
//output
System.out.print("Change for "+amountToChange+" = ");
//run through the list of coins that we have and display each.
for(Integer count: coinsUsed){
System.out.print(count + " ");
}
System.out.println();
//pass this back to be tallied
return 1;
}
/*
* Check to see if we overshot the amountToBeChanged
*/
if (amountSoFar > amountToChange)
{
//this branch was unsuccessful
return 0;
}
//this holds the sum of the branches that we send below it
int successes=0;
// Pass through each coin to be used
for (Integer coin:coinAmounts)
{
//we only want to work on currentCoin and the coins after it
if (coin >= currentCoin)
{
//copy the list so we can branch from it
List<Integer> copyOfCoinsUsed = new ArrayList<Integer>(coinsUsed);
//add on one of our current coins
copyOfCoinsUsed.add(coin);
//branch and then collect successful attempts
successes += change(copyOfCoinsUsed, coin, amountSoFar + coin, amountToChange);
}
}
//pass back the current
return successes;
}