ArrayList in Java and inputting - java

I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.
Two Questions:
I can't seem to get the input loop to work out, what's the best practice for doing so.
What is the object-type going to be for the reading method? A double[], or an ArrayList?
How do I declare method-type to be an arraylist?
How do I prevent the array from having more than 1000 values stored within it?
Let me show what I have so far:
public static java.util.ArrayList readRange(double end_signal){
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
System.out.println(input); //debugging
++count;
} while(input(--count) != end_signal);
return input;
}
Any help would be appreciated, pardon my newbieness...

What you need in your loop condition is:
while ( input.get( input.size()-1 ) != end_signal );
What you're doing is decrementing the counter variable.
Also you should declare the ArrayList like so:
ArrayList<Double> list = new ArrayList<Double>();
This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.

Answers:
>1. I can't seem to get the input loop to work out, what's the best practice for doing so.
I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read:
while the read number is not end signal and count is lower than limit: do.
>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?
An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation.
>2.1How do I declare method-type to be an arraylist?
See code below.
>2.2. How do I prevent the array from having more than 1000 values stored within it?
By adding this restriction in the while condition.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class InputTest{
private int INPUT_LIMIT = 10000;
public static void main( String [] args ) {
InputTest test = new InputTest();
System.out.println("Start typing numbers...");
List list = test.readRange( 2.0 );
System.out.println("The input was " + list );
}
/**
* Read from the standar input until endSignal number is typed.
* Also limits the amount of entered numbers to 10000;
* #return a list with the numbers.
*/
public List readRange( double endSignal ) {
List<Double> input = new ArrayList<Double>();
Scanner kdb = new Scanner( System.in );
int count = 0;
double number = 0;
while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){
System.out.println( number );
input.add( number );
}
return input;
}
}
Final remarks:
It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class
In java code style the variable names should go in cammel case like in "endSignal" rather than "end_signal"

I think you started out not bad, but here is my suggestion. I'll highlight the important differences and points below the code:
package console;
import java.util.;
import java.util.regex.;
public class ArrayListInput {
public ArrayListInput() {
// as list
List<Double> readRange = readRange(1.5);
System.out.println(readRange);
// converted to an array
Double[] asArray = readRange.toArray(new Double[] {});
System.out.println(Arrays.toString(asArray));
}
public static List<Double> readRange(double endWith) {
String endSignal = String.valueOf(endWith);
List<Double> result = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
String next;
while (!(next = input.next().trim()).equals(endSignal)) {
if (isDouble(next)) {
Double doubleValue = Double.valueOf(next);
result.add(doubleValue);
System.out.println("> Input valid: " + doubleValue);
} else {
System.err.println("> Input invalid! Try again");
}
}
// result.add(endWith); // uncomment, if last input should be in the result
return result;
}
public static boolean isDouble(String in) {
return Pattern.matches(fpRegex, in);
}
public static void main(String[] args) {
new ArrayListInput();
}
private static final String Digits = "(\\p{Digit}+)";
private static final String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
private static final String Exp = "[eE][+-]?" + Digits;
private static final String fpRegex = ("[\\x00-\\x20]*" + // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from the Java Language Specification, 2nd
// edition, section 3.10.2.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|" +
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.(" + Digits + ")(" + Exp + ")?)|" +
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent
// FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional
// trailing
// "whitespace"
}
In Java it's a good thing to use generics. This way you give the compiler and virtual machine a hint about the types you are about to use. In this case its double and by declaring the resulting List to contain double values,
you are able to use the values without casting/type conversion:
if (!readRange.isEmpty()) {
double last = readRange.get(readRange.size() - 1);
}
It's better to return Interfaces when working with Java collections, as there are many implementations of specific lists (LinkedList, SynchronizedLists, ...). So if you need another type of List later on, you can easy change the concrete implementation inside the method and you don't need to change any further code.
You may wonder why the while control statement works, but as you see, there are brackets around next = input.next().trim(). This way the variable assignment takes place right before the conditional testing. Also a trim takes playe to avoid whitespacing issues
I'm not using nextDouble() here because whenever a user would input something that's not a double, well, you will get an exception. By using String I'm able to parse whatever input a user gives but also to test against the end signal.
To be sure, a user really inputed a double, I used a regular expression from the JavaDoc of the Double.valueOf() method. If this expression matches, the value is converted, if not an error message will be printed.
You used a counter for reasons I don't see in your code. If you want to know how many values have been inputed successfully, just call readRange.size().
If you want to work on with an array, the second part of the constructor shows out how to convert it.
I hope you're not confused by me mixin up double and Double, but thanks to Java 1.5 feature Auto-Boxing this is no problem. And as Scanner.next() will never return null (afaik), this should't be a problem at all.
If you want to limit the size of the Array, use
Okay, I hope you're finding my solution and explanations usefull, use result.size() as indicator and the keyword break to leave the while control statement.
Greetz, GHad

**
public static java.util.ArrayList readRange(double end_signal) {
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner(System. in );
int count = 0;
do {
input.add(Double.valueOf(kbd.next()));
System.out.println(input); //debugging
++count;
} while (input(--count) != end_signal);
return input;
}
**

public static ArrayList<Double> readRange(double end_signal) {
ArrayList<Double> input = new ArrayList<Double>();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
++count;
} while(input(--count) != end_signal);
return input;
}

Related

Using only 1 System.out.print() instead of 3. More details below [duplicate]

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

String.replace isn't working

import java.util.Scanner;
public class CashSplitter {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Cash Values");
String i = S.nextLine();
for(int b = 0;b<i.length(); b ++){
System.out.println(b);
System.out.println(i.substring(0,i.indexOf('.')+3));
i.replace(i.substring(0, i.indexOf('.') + 3), "");
System.out.println(i);
System.out.println(i.substring(0, i.indexOf('.') + 3));
}
}
}
The code should be able to take a string with multiple cash values and split them up, into individual values. For example 7.32869.32 should split out 7.32, 869.32 etc
A string is immutable, therefore replace returns a new String for you to use
try
i = i.replace(i.substring(0, i.indexOf('.') + 3), "");
Although try using
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
There are several problems with your code:
You want to add two, not three, to the index of the decimal point,
You cannot use replace without assigning back to the string,
Your code assumes that there are no identical cash values.
For the last point, if you start with 2.222.222.22, you would get only one cash value instead of three, because replace would drop all three matches.
Java offers a nice way of splitting a String on a regex:
String[] parts = S.split("(?<=[.]..)")
Demo.
The regex is a look-behind that expects a dot followed by any two characters.

Java substring difficulty

I know how to use substring() but why isn't this working, the user inputs an equation like
"5t + 1" with a space before and after the "+". I want tVariable to hold the integer before it, in this case 5 and constant should hold the constant integer in this case 1, but I get an out of range error.
import java.util.*;
import javax.swing.JOptionPane;
public class project3030 {
public static void main(String[] args) {
String L1x, tVariable, constant;
L1x = JOptionPane.showInputDialog("This is the format (x=5t + 1)");
int endIndex = L1x.indexOf("t");
tVariable = L1x.substring(0, endIndex);
int beginIndex = L1x.lastIndexOf(" ");
int endIndex2 = L1x.indexOf("");
constant = L1x.substring(beginIndex, endIndex2);
System.out.println(tVariable + constant);
}
}
You need to change it to something more like
constant = L1x.substring(L1x.lastIndexOf(" ")).trim();
Then when you add the numbers, you have to Parse them before you add them.
int constantInt = Integer.parseInt(constant);
Or you could use this solution:
String[] input = L1x.split(" ");
// remove the 't'
String tNum = input[0].substring(0, input[0].length() - 1);
int t = Integer.parseInt(tNum);
int constant = Integer.parseInt(input[2]);
String operator = input[1];
if (operator == "-")
constant *= -1;
The reason you are getting this error is because your substring() range is off.
You are passing into substring() an invalid range because the first index is beginIndex which you set equal to lastIndexOf(" ") while endIndex2 you set equal to indexOf("") which will occur at the beginning of the string.
Thus, you have your ranges mixed up. When you make this statement:
constant = L1x.substring(beginIndex, endIndex2);
You're giving it an invaid range
and will cause the specified error.
You could also do it different way. Let's say you create a JFrame and there you could put a textfield for every value, so for every "t" or constants, and then it would be much more simple to get those values. For characters like t or = you could use JLabels, so it would be a mixture of JTextFields and JLabels and I think it wouldn't be that ugly. I used this solution few times.

How to display a list of ints and display total cost

This is my current code:
public static void Costs(float[] args) {
Scanner Costs = new Scanner(System.in);
String Item1Cost;
System.out.print("Enter the cost of Item 1 £");
Item1Cost = Costs.next();
String Item2Cost;
System.out.print("Enter the cost of Item 2 £");
Item2Cost = Costs.next();
String TotalCost;
TotalCost = Item1Cost + ", " + Item2Cost;
System.out.println("The cost of each of your items in order is: " + TotalCost);
}
I am trying to change it so that it obtains an int form the user and displays all the prices, and also totals them.
When trying my self I used this, and I could get the 'costs' stored them in a string and display them but I can not make a total with this code. I was wondering if someone could give me a hand. I'm sure the answer is pretty simple, but I'm fairly new to java and I just cant think of a solution.
So what you're doing at the moment is String concatenation. This is where you simply stick two String objects on the end of one another, and create a new String from that. This happens because, in Java the + operator is overloaded. This means that it expresses different functionality depending on the type of the operands.
Example of overloaded operator
String str = "Hello ";
String str2 = "World.";
String sentence = str + str2; // Sentence equals "Hello World."
int num1 = 5;
int num2 = 7;
int total = num1 + num2; // Same operator, but total equals 12, not 57.
What you need to do in your example is cast the operands to the correct types, so that Java knows how to work on them. That is, it overloads + to the correct functionality.
Example
int item1Cost = costs.nextInt(); //Notice the java naming conventions.
int item2Cost = costs.nextInt();
System.out.println("Total cost: " + (item1Cost + item2Cost));
Or you can pull the value in as a String and perform some validation. This is a safer option because it means you can control program flow easier.
String item1CostStr = costs.nextLine();
int item1Cost = 0;
if(item1CostStr.matches("[0-9]+")) {
item1Cost = Integer.parseInt(item1CostStr);
}
to convert an string to an int and operate with it, you should use this method:
Integer.parseInt(string);
That method returns an int.
Hope it helps!
If you want the input as an integer, use scan.nextInt() instead. Then it should work just fine.
This is a weird line of code though:
TotalCost = Item1Cost + ", " + Item2Cost;
What is it supposed to do? This won't compile if you're using integers.
Sidenote: use the java naming conventions. Variable names should start with a lowercase letter.

Extracting characters from a string and putting into specific arrays by type

I'm new to Java so I'm trying to write random programs to figure it out. I'm trying to write something that takes as user-input a quadratic equation like so: x^2 + 3x -1
Maybe this is too advanced (or maybe it isn't) but I'm wondering how to extract the characters one-by-one in a loop. If it was all digits I think I could use .isDigit() and save them to an array, but because they're different data types I'm not sure how to go about doing this. My 'code' so far looks like this
import java.lang.String;
import java.lang.StringBuffer;
import java.util.Scanner;
import java.lang.Character;
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[];
String lettArr[];
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i);
if (request.isDigit(c))
{
myArr[1] += c;
}
if(request.isLowerCase(c))
{
lettArr[1] += c;
}
}
System.out.println(myArr[0]);
}
}
my .isDigit() and .isLowerCase() methods are not working. I think I'm using them in the right sense. This is pretty complex for my level and I'm wondering if this is a dead-end or an acceptable strategy.
Thanks.
I think what your are trying to do is to extract the coefficients from the user input. Your approach might work but there would be many case that you have to consider (+/- signs for example). Instead why don't you try Java's regular expressions
String input = "2x^2 - 4x + 1";
input = input.replaceAll("\\s", ""); //removes all whitespaces
Pattern p = Pattern.compile("(-?\\d+)x\\^2((\\+|-)\\d+)x((\\+|-)\\d+)");
Matcher m = p.matcher(input);
if (!m.matches()) {
System.out.println("Incorrect input");
return;
}
int a, b, c;
a = Integer.parseInt(m.group(1));
b = Integer.parseInt(m.group(2));
c = Integer.parseInt(m.group(4));
System.out.println(String.format("a=%d, b=%d, c=%d", a, b, c));
You can adapt this fragment and use it in your code. I , however, supposed that your coefficients are integer numbers. If you need them, instead, to be double you have to change the format of the given regex and also to change Integer.parseInt to Double.parseDouble. I could write this in more details if you are interested.
There are a few things wrong with your code:
public class Lab
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Please input the quadratic equation (ex: 2x^2 + 3x - 2): ");
String request = user_input.nextLine();
int myArr[]; //not initialized
String lettArr[]; //should be a character type & not initialized
for (int i = 0; i <= request.length(); i++)
{
String c = request.charAt(i); // returns a char
if (request.isDigit(c))
{
myArr[1] += c; // not right, myArr is ints and c is a char
}
if(request.isLowerCase(c))
{
lettArr[1] += c; // not right
}
}
System.out.println(myArr[0]); //only prints one char (you might want this
}
}
1.
You are extracting a character from the input string and trying to add it to the second entry in an uninitialized array. You're line in code is:
myArr[1] += c;
myArr is an integer array and c is a character. You can't do that in java. What's more, you are trying to add a char to an int, which was not initialized in the first place!! The type of everything in an array must be the same. This gets more complicated when it comes to inheritance and such, but for now just know that you can't do that. If you wanted the Integer value of a character you can use:
Integer.parseInt(c)
I'm not sure what you are trying to do with your statement, but I'm 90% sure that it's not trying to do what you want it to. For reference:
myCharArr[i] = c;
assigns the i-th element (starting from 0) to the value of c. So if i=1 and myCharArr was initialized to 3 elements long, it would look like this:
[ ? | c | ?]
where ? is just a garbage value.
2.
In java you need to initialize your arrays, or use a more dynamic List object. The thing with primitive arrays is that their size cannot change, i.e. when an primitive array is initialized:
int arr[] = new int[5];
it stays the same size (in this case 5). If you use something like an ArrayList, you can add as many things as you want. The way you would initialize ArrayLists would be like:
ArrayList<Integer> intArr = new ArrayList<Integer>();
ArrayList<Character> charArr = new ArrayList<Character();
and with those initialized you can do:
intArr.add(someInt);
charArr.add(someChar);
You can use primitive arrays for this problem but it will save you a bit of trouble if you use Lists.
Read up on arrays.

Categories