Im writing a binary search tree. The user will use the program as follows:
Which tree would you like to test (BST, ST, RBT)?
BST
How many items would you like to insert?
10000
Pattern (random or sorted)?
sorted
Next command (insert X, delete X, find X, height, quit)?
find 111111
Item not present.
For the first three choices i figure i can just use strings to choose between BST, ST and RBT as wel as to choose between random or sorted, somthing like
String choice
if( choice == "random")
insert random numbers
what im having trouble with is the 4th choice. if the user enters insert 100 as a string, for example, would i just have to take the 100 off and make it an int. and if so, how would i go about doing that?
You can use the combination of the functions to determine whether a string is an int or not
public boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}
If this function returns true ... string is an integer ... now get the integer value using
Integer.parseInt(str);
First thing I want to note is that a String should not be compared with ==, rather you should use string.equals(comparedString); You can also use the following code to parse through all the inputs that a person enters, and then use both the string entered and the string value entered and it would not be dependent on the start of the string. This would satisfy the options for them all; insert, delete, ect.
String userInput;//received by system in
String choice;
int choiceInt;
for (int i = 0; i < userInput.length(); i++)
{
Character character = userInput.charAt(i);
if (!Character.isDigit(character))
{
choice += character;
}
else if (Character.isDigit(character))
{
choiceInt += character;
}
else
{
System.out.println("Unable to determine character.");
}
/* Code for the comparison of String based option */
//Example
if (choice.equalsIgnoreCase("insert")//NOTE: the ignore case,
// you want users to be
// able to enter in strings
// and not have a case sensitivity.
{
/* do the code you planned on doing here */
}
}
You could also assign integer values for each String possibility that you are willing to accept as valid options. This would increase the coding but also would also for a switch case statement. (which is still interpreted as if, else if, else statements) I think at that point it would be more up to the developers intentions and design preferences. Please correct me if I am wrong.
You can also replace the final else statement by either using a try and catch block.
Try this:
if (input.startsWith("insert")) {
int num = Integer.parseInt(input.replaceAll("\\D", ""));
}
Related
I was asked to make a program which takes an array of string and sort it alphabetically. The program should not accept a string with digit or a string of length bigger than 10. If a string does not fulfill requirements the program tells to user to enter another on. After that, all strings will be turn into uppercases strings, and we sort the array. Here's my program, but it doesn't run quite well.
It does compile but if a string contains digit or if the length is bigger than 10, it stop and does not ask the user to enter another string. I've tried to do it as asked but I end with an infinite loop that's why I've put a Sys.exit –
I wan't to know fist if this program is good or if someone has a more simple way to that. How to modify this program the way that the user is asked to enter another string when one entered is wrong?
Any advise or any alternative program.
Thanks.
static boolean arrayFilter(String[] str) {
for (int i=0 ; i < str.length ; i++) {
for( char c:str[i].toCharArray()) {
if((Character.isDigit(c))||(str[i].length()>=10))
return false;
}
}
return true;
}
static void swap(int i,int j,String[] str) {
String tmp;
tmp=str[i];
str[i]=str[j];
str[j]=tmp;
}
static String[] capitalize(String[] str) {
for(int i=0;i<str.length;i++) {
str[i]=str[i].toUpperCase();
}
return str;
}
static String[] triTab(String[] str) {
if(arrayFilter(str)==false) {
System.out.println("Wrong string array, please enter list of string without digit and length at most 10");
System.exit(0);
}
else {
str=capitalize(str);
for(int i=0;i<str.length;i++) {
for(int j=i+1;j<str.length;j++) {
if(str[i].compareTo(str[j])>0)
swap(i,j,str);
}
}}
return str;
}
} ```
You actually have several problems.
First, move your check for a valid array when someone enters it.
// prompt for use array first time.
while (arrayFilter(str) == false) { // or while(!ArrayFilter(str)) {
System.out.println(
"Wrong string array, please enter list of string without digit and length at most 10");
// prompt for new array
// the while loop will exit when the array is valid.
}
// Array okay so invoke the sort method.
The other problem is that you are changing the nature of the array. They are now all uppercase. Instead of using compareTo use compareToIgnoreCase. Then you can eliminate the method for converting to all uppercase.
... if instead of a number I get a letter, or a symbol, or 2 decimals.
I am making a change maker program in java.
Everything works good, the only thing i am confused about is checking the string to see if is invalid for my use,
I did this for when is left empty;
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid input! ");
System.exit(0);
}
That works perfect, now how can I do the else to check for letters or dots or symbols, anything that is not a number?
You could use regular expressions.
Here's some sample code to check for digits only (\\d) in your input string.
The code that actually checks is pattern.matcher(in).matches() and it tries to match the regular expression defined by regex
Let me know if you need more explanations
public class HelloWorld{
public static void main(String[] args) {
String regex = "\\d+";
String inputNumber = "2";
String inputDecimal = "2.0";
String inputString = "two";
String[] inputs = {inputDecimal, inputNumber, inputString };
Pattern pattern = Pattern.compile(regex);
for(String in: inputs){
System.out.print( in + " ");
System.out.print( pattern.matcher(in).matches()? "":"does not");
System.out.print( " contain integer numbers" );
System.out.println("---");
}
}
}
If you need to perform all the processing only when the String is integer why not check for integer value in the if clause and let the else clause be common for all the letter, dots, symbols and also empty.
if(s1.isNum){
//all processing here
}
else{
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Otherwise you could also use try and catch block.
try{
int num= Integer.parseInt(s1);
//rest of the processing
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Use either according to your requirement
You could use a regular expression1 and String.matches(String) which Tells whether or not this string matches the given regular expression. \\d+ should match one or more digits. Something like
System.out.println("12".matches("\\d+"));
Prints
true
1Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems. --jwz
To test whether it is an integer, parse it to an int like this:
Integer.parseInt(s1)
You might also want to make use of the value returned but I don't show it here. Now you can apply try catch blocks around the method call and catch NumberFormatException like this:
try {
Integer.parseInt(s1);
//The code here will run if s1 is an integer.
} catch (NumberFormatException e) {
//this will be executed when s1 is not an integer
}
You can also extract a method from the above code. A method that returns true when the exception is not thrown. However, a disadvantage of try catch is that throwing an exception needs time and thus, it slows down your program.
To test whether the string is a letter, you loop through all the chars in the string and use one of the methods of the Character class.
boolean isLetter = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isLetter(s1.charAt(i))) {
isLetter = false;
break;
}
}
If isLetter is true, it is a letter. Again, you can also extract this as a method.
To check whether it is a symbol, use one of the methods of the Character class (again).
boolean isSymb = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isJavaIdentifierStart(s1.charAt(i))) {
isSymb = false;
break;
}
}
To check for dots in a string, just use
s1.contains(".")
Isn't that simple?
Ok, I solved the problem the following way... I took a little bit of every idea lol...
if (s1 == null) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
for (int i = 0; i < s1.length(); i = i + 1) {
if (!Character.isDigit(s1.charAt(i))) {
JOptionPane.showMessageDialog(null, "You must enter an integer value");
System.exit(0);
}
}
I have a method I'm using to validate user-inputted values in a program. Whenever the user inputs a string into a JOptionPane, I call this method and pass in the inputted string, plus the maximum and minimum values I need their input to be between. First I check if the input is an integer by trying to parse the input string and catching exceptions, then I check if the integer is between the min and max. My problem is that if the user inputs another incorrect non-integer value after being prompted, I don't know how to check if the new value is correct or not. Here is the method, can anybody help?
int checkInput(String input, int min, int max) {
Boolean isInteger = false;
Boolean inputAccepted = false;
int userInput = 0; //will be set later
while (!isInteger) {
try
{
userInput = Integer.parseInt(input);
}
catch (NumberFormatException e)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
isInteger = true; //the problem here is that it assumes the user inputted a correct value after being prompted... what if they enter another incorrect value?
}
}
while (!inputAccepted) {
if (userInput < min || userInput > max)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
}
else
{
inputAccepted = true;
}
}
return userInput;
}
I believe the main problem is that you have a method whose job isn't simple and well-defined. It looks like you have a statement outside this method that inputs a number; but checkInput has two jobs: making sure the number is valid, and inputting more numbers until it is. This is a problem in two ways: your code that does the input is duplicated in two places, and you have a method whose responsibility isn't clear.
Instead, try writing a method that just checks whether the input is valid, and returns true or false. I'd change the name to isValidInput. The caller would then have a loop that would perform the input, make sure it's valid, and go back if it isn't.
Usually I wouldn't answer a question like this by pointing to flaws in your design. But I think that in this case, if you rethink your design, your question will answer itself. (That's often the case when you design things correctly--things fall into place.)
Your checkInput() function should throw its own exception if the input is not correct. Spliting the code into a validator and a parser would result in parsing the input twice.
I've got a problem here that's been giving me some real trouble and I really cant even get an idea of what to do. here's the assignment and my code so far.
Create a system using an ArrayList which stores and manipulates names.
Using standard input constantly prompt user for the following ..
Enter command or quit: (if they enter quit -- quit program)
Commands:
add <name>: add the String <name> to ArrayList;
change <name> <newName>: change all items in ArrayList which
have <name> to <newName>;
delete <name>: delete all items in Arraylist which are <name>;
print: print the ArrayList;
amount: display the amount of items in ArrayList.
System must work... and have proper error messages..
import java.util.*;
public class NameManipulation {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter a command, or quit!");
ArrayList<String> names = new ArrayList<String>();
String command = console.next();
int size = names.size();
for (String x = null; size; x++) {
if (command == "add") {
String assignment = console.next();
names.add(assignment);
}
if (command == "change") {
String newname = console.next();
names.set(names.size, newname);
}
if (command == "delete") {
String delete = console.next();
if (delete == names)
;
names.remove();
}
if (command == "print") {
System.out.println(names);
}
if (command == "amount") {
amount = (names.size - 1);
System.out.println(amount);
}
if (command == "quit") {
System.out.println("You just quit!");
break;
} else
System.out.println("command not found!");
System.out.println(names);
}
}
}
Don't use == (in Java that tests reference equality); you want to test for object value equality (and I suggest case-insensitivity) so you want to use String.equalsIgnoreCase and you should probably use else if for the other tests - for one example,
if(command.equalsIgnoreCase("add")) {
String assignment = console.next();
names.add(assignment);
} else if // ...
Also, this is just wrong;
for (String x = null; size; x++) // null++ is going to give you a bad time.
I think you wanted
for (int x = 0; x < size; x++)
Just looking at this it seems like it has a lot of problems...
In the for loop you're initializing a String to null and then trying to increment it (x++). I don't think that's legal syntax. Also, your for loop condition is set to size, which will initially be equal to 0. I'd have to test it, but the 0 may evaluate to false, which means the loop would never execute.
You don't want a for loop anyway, probably a do-while loop that runs until the command is equal to "quit" do{}while(!command.equals("quit"));
You should be using .equals() instead of '==' as was mentioned by Elliot Frisch. Also ignoring case is good, and you should be using else ifs.
In the change command you should be parsing out two parameters -- both the name to replace and the new name, and then perform the replacement. Right now you have the first parameter as names.size, which I think will be outside the bounds of the list (names.size() - 1 should be the last element). Instead you should get the index of the name you're replacing.
Depending on Java's toString implementation of ArrayList it may print out names nicely or it might be something like "#ArrayList Object" - I think Java has a nice ArrayList toString method though so that may work.
On the print amount, you should be using names.size() instead of names.size() - 1 (because names.size() - 1 will give you one less item than what is actually in the list)
you could try and use a switch block that could stream line your control statements. As stated above learn when to use == and when to use the .equals(). One compares a reference (==) the other compares the memory location, the important thing to take away from this, is that a String is an object and when you create a new String, it compares the address rather than a value (forgive me if i am wrong).
switch(command){
case "add": names.add(assignment);
break;
case "change": ..... etc.
}
If I were trying to accomplish this task I would use a List, not an ArrayList. I hope this method helps! This is C# code. I don't know the exact Java syntax but it seemed as if a lot of it was similar. I hope this methodology helps!
static void Main(string[] args)
{
string statement = "";
bool executed_command_properly;
while (statement != "quit")
{
executed_command_properly = false;
statement = Console.ReadLine();
string[] my_statement_elements = statement.Split(' ');
string command = my_statement_elements[0];
//could possibly use an array for inputs
string input1 = my_statement_elements[1];
string input2 = my_statement_elements[2];
switch(command)
{
case "add":
// do stuff
executed_command_properly = true;
break;
//other cases
}
if (executed_command_properly != true)
{
//error messages
}
}
}
I am making an inefficient calculator type of program that takes values from user defined arrays and plugs them into an equation that the user also defines. To do this I needed to make my program change my string to a char array, the problem? I have it so that users must use A1-10 to reference the definded index and I cannot find a way to make the program search the next array for the number to specify what array the program is accessing.
out.println("Please input a string of commands in a format similar to this: ");
out.println("([A1]-[A2]=) or ([A8]+[A6]=) or ([A1]-[A4]+[A7]*[A10]/[A3]=)");
out.println("Use only the numbers 1-10 when referencing an array. \n You may always type in 'Help' if you need help. ");
String eString = scn.nextLine();
if ("help".equals(eString)) {
out.println("Figure it our yourself...");
} else {
for (char c: eString.toCharArray()) {
if (c == 'A') {
}
}
the code got a little jumbled up while changing code and I haven't taken the time to make it look nice and pearly again.
If you need the index you should just use a normal for loop instead of an enhanced for loop.
char[] input = eString.toCharArray();
for(int i = 0; i < input.length; i++) {
if(input[i] == 'A'){
// You know the index of A here.
}
}
You should also use "help".equalsIgnoreCase(eString) when comparing with help so that they can enter either "Help" or "help" (link to doc)