Code doesn't allow the user to input letters - java

So far I have a code that asks for a user input but a part of my code isn't accepting letters as inputs. For example if i type in say woah123 it'll give me a number format exception. Any way to get around this? Error is at the second line int i = Integer.parseInt(sentence).
Sentence is the user input
sentence.replaceAll("\\D", "");
int i = Integer.parseInt(sentence);
i = i * 2 ;
woah.replaceAll("\\d", "" + i);
System.out.println(woah);

Strings are immutable.
Generally, every modification you made on an immutable object will "give" you another immutable object.
So it should be :
sentence = sentence.replaceAll("\\D", "");
Indeed you have to do the same for woah.
You may read about what is an immutable object.

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

Extra java input validation for strings

I want to make this so that short inputs can still be detected, such as "Londo" and "Lon", but want to keep it small and use it without basically copying and pasting the code, any tips? thank you.
if (Menu.answer1.equals("London"))
{
if (location.equals("London")) {
System.out.print(location + " ");
System.out.print(date + " ");
System.out.print(degrees + "C ");
System.out.print(wind + "MPH ");
System.out.print(winddirection + " ");
System.out.print(weather + " ");
System.out.println("");
}
You can use startsWith()
String city = "London";
if (city.startsWith("Lon")) {
// do something
}
Also if you need to check some substring, you can use contains method:
Menu.answer1 = "London";
Menu.answer1.contains("ondo"); // true
If you want to check against a fixed set of alternatives, you may use a list of valid inputs using contains:
List<String> londonNames = Arrays.asList("London", "Londo", "Lon");
if (londonNames.contains(Menu.answer1)) {
...
}
You can use (case-insensitive) regex to do the same, e.g.:
(?)Lon[a-z]{0,3} where
(?) = case insensitivity
Lon = Initial 3 characters
[a-z]{0,3} = any number of alphabets between 0 and 3
Here's an example:
String regex = "(?)Lon[a-z]{0,3}";
System.out.println("London".matches(regex));
System.out.println("Lond".matches(regex));
System.out.println("Lon".matches(regex));
If the underlying problem is that the user can enter one of several names, and you want to allow abbreviations, then a fairly standard approach is to have a table of acceptable names.
Given the user input, loop through the table testing "does the table entry start with the string typed by the user?" (like one of the previous answers here). If yes, then you have a potential match.
Keep looking. If you get a second match then the user input was ambiguous and should be rejected.
As a bonus, you can collect all names that match, and then use them in an error message. ("Pick one of London, Lonfoo, Lonbar").
This approach has the advantage (compared to a long chain of if-then-else logic) of not requiring you to write more code when all you want to do is have more data.
It automatically allows the shortest unique abbreviation, and will adjust when a once-unique abbreviation is no longer unique because of newly-added names.

Questions regarding programming a single-line calculator in Java

I am currently a early CS student and have begun to start projects outside of class just to gain more experience. I thought I would try and design a calculator.
However, instead of using prompts like "Input a number" etc. I wanted to design one that would take an input of for example "1+2+3" and then output the answer.
I have made some progress, but I am stuck on how to make the calculator more flexible.
Scanner userInput = new Scanner(System.in);
String tempString = userInput.nextLine();
String calcString[] = tempString.split("");
Here, I take the user's input, 1+2+3 as a String that is then stored in tempString. I then split it and put it into the calcString array.
This works out fine, I get "1+2+3" when printing out all elements of calcString[].
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
I then convert the integer parts of calcString[] to actual integers by putting them into a integer array.
This gives me "1 0 2 0 3", where the zeroes are where the operators should eventually be.
if (calcString[1].equals("+") && calcString[3].equals("+")) {
int retVal = calcIntegers[0] + calcIntegers[2] + calcIntegers[4];
System.out.print(retVal);
}
This is where I am kind of stuck. This works out fine, but obviously isn't very flexible, as it doesn't account for multiple operators at the same like 1 / 2 * 3 - 4.
Furthermore, I'm not sure how to expand the calculator to take in longer lines. I have noticed a pattern where the even elements will contain numbers, and then odd elements contain the operators. However, I'm not sure how to implement this so that it will convert all even elements to their integer counterparts, and all the odd elements to their actual operators, then combine the two.
Hopefully you guys can throw me some tips or hints to help me with this! Thanks for your time, sorry for the somewhat long question.
Create the string to hold the expression :
String expr = "1 + 2 / 3 * 4"; //or something else
Use the String method .split() :
String tokens = expr.split(" ");
for loop through the tokens array and if you encounter a number add it to a stack. If you encounter an operator AND there are two numbers on the stack, pop them off and operate on them and then push back to the stack. Keep looping until no more tokens are available. At the end, there will only be one number left on the stack and that is the answer.
The "stack" in java can be represented by an ArrayList and you can add() to push items onto the stack and then you can use list.get(list.size()-1); list.remove(list.size()-1) as the pop.
You are taking input from user and it can be 2 digit number too.
so
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
will not work for 2 digit number as your modification is i+=2.
Better way to check for range of number for each char present in string. You can use condition based ASCII values.
Since you have separated your entire input into strings, what you should do is check where the operations appear in your calcString array.
You can use this regex to check if any particular String is an operation:
Pattern.matches("[+-[*/]]",operation )
where operation is a String value in calcString
Use this check to seperate values and operations, by first checking if any elements qualify this check. Then club together the values that do not qualify.
For example,
If user inputs
4*51/6-3
You should find that calcString[1],calcString[4] and calcString[6] are operations.
Then you should find the values you need to perform operations on by consolidating neighboring digits that are not separated by operations. In the above example, you must consolidate calcString[2] and calcString[3]
To consolidate such digits you can use a function like the following:
public int consolidate(int startPosition, int endPosition, ArrayList list)
{
int number = list.get(endPosition);
int power = 10;
for(int i=endPosition-1; i>=startPosition; i--)
{
number = number + (power*(list.get(i)));
power*=10;
}
return number;
}
where startPosition is the position where you encounter the first digit in the list, or immediately following an operation,
and endPosition is the last position in the list till which you have not encountered another operation.
Your ArrayList containing user input must also be passed as an input here!
In the example above you can consolidate calcString[2] and calcString[3] by calling:
consolidate(2,3,calcString)
Remember to verify that only integers exist between the mentioned positions in calcString!
REMEMBER!
You should account for a situation where the user enters multiple operations consecutively.
You need a priority processing algorithm based on the BODMAS (Bracket of, Division, Multiplication, Addition and Subtraction) or other mathematical rule of your preference.
Remember to specify that your program handles only +, -, * and /. And not power, root, etc. functions.
Take care of the data structures you are using according to the range of inputs you are expecting. A Java int will handle values in the range of +/- 2,147,483,647!

Strings for Calculator

I want to write a calculator that takes the numbers from text fields and adds them together to give them out in a text area.
It works as far as taking the two numbers from the text fields, but when I add them together it will give out: 1+1=11.
How can I add the two strings so it will equal 2?
This is my source code:
private void ButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {
String Nummer1 = Zahl1.getText();
String Nummer2 = Zahl2.getText();
int intZahl1 = Integer.parseInt(Nummer1);
Integer integerZahl1 = new Integer(Nummer1);
int intZahl2 = Integer.parseInt(Nummer2);
Integer integerZahl2 = new Integer(Nummer2);
Result.setText(Nummer1 + Nummer2);
Result is the name of my text area and the divers Nummers are just variables, as you may have noticed already.
You're adding the Strings not the ints. You will want to add integerZahl1 and intZahl2 instead of Nummer1 and Nummer2.
For example,
int intResult = intZahl1 + intZahl2;
Result.setText(String.valueOf(intResult));
Also as an aside, you'll want to learn and follow Java naming conventions. Variable and method names should start with a lower-case letter, and class names should start with an upper-case letter.
Dom states:
Or you could just do Result.setText(intZahl1 + intZahl2); if you only need to display the result.
Dom, please understand that setText(...) requires a String parameter, not an int, so your method call will not be allowed by the compiler. If one tries the trick of
Result.setText("" + intZahl + intZahl2);
they'd get 11 again. For your technique to work, you'd need to do something like,
Result.setText(String.valueOf(intZahl1 + intZahl2));
Edit
Also you will want to use ints and not Integers.

Can't replace a letter in a string

I have asked a couple of questions about this for loop:
String[] book = new String [ISBN_NUM];
bookNum.replaceAll("-","");
if (bookNum.length()!=ISBN_NUM)
throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
for (int i=0;i<bookNum.length();i++)
{
if (Character.isDigit(bookNum.charAt(i)))
book[j]=bookNum.charAt(i); //this is the problem right here
j++;
if (book[9].isNotDigit()||
book[9]!="x" ||
book[9]!="X")
throw new ISBNException ("ISBN " + bookNum + " must contain all digits" +
"or 'X' in the last position");
}
which will not compile. An answer I had from the other question I asked told me that the line where the error occurs is wrong in that bookNum.charAt(i) is an (immutable) string, and I can't get the values into a book array that way. What I need to do on my assignment is check an ISBN number (bookNum) to see that it is all numbers, except the last digit can be an 'x' (valid ISBN). Is this the best way to do it? If so, what the hell am I doing wrong? If not, what method would be a better one to use?
book is of type String[] (array of strings), bookNum.charAt(i) returns a char. You can't assign a String from a char.
Do book[j] = String.valueOf(bookNum.charAt(i)) instead.
Also you might want to change the first error:
throw new ISBNException ("ISBN "+ bookNum + " must be " + ISBN_NUM + " characters");
The book[] array contains Strings.
The method bookNum.charAt() returns a char.
You can't assign a char to a member of a String array.
If you want an array of Strings, consider using bookNum.substring( i, i + 1 ).
What you are doing wrong is that you declare book as a String Array instead of just a String.
Here is the problem :
String[] book = new String [ISBN_NUM];
You create an array of String objects, but then you feed it with chars :
book[j]=bookNum.charAt(i);
Just initialize the array like this :
char[] book = new char[ISBN_NUM];
Furthermore, you should get rid of your j variable that does the same as i. And end the for loop before checking book[9] or you will get a NullPointerException.
Hopefully there are not any more problems :)
See my answer in your other thread.
You are basically treating an array of strings like a string (or array of characters). What is your goal here? You just want to validate that the bookNum is a valid ISBN, correct? What is the course of action if it is not? If your goal is to take the whole bookNum if it is valid and abort if it isn't, my answer in the other thread should give hints as to a possibly better way to do that.

Categories