Java Program Using Split to Validate Input. Simplifying, But Keeping Things Fuctional - java

Any help would be appreciated.
I am not trying to list the operators, ( I know that it would work that way) i want to know if i can put them in a bundle as i attempted in my code below (it did not work, anyone knows why? how to fix it?):
}
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
String operator = token[1];//this is the operator
if (operator.equals(function)){
for (int i = 0; i<length; i++) {
}
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}

first you should split .you can't access token[0] before declare tokens
String function = "[+\\-*/]+"; //this
String[] token = input.split(function );//and this
then use array[index]
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
edit....
you should use .matches instead .equals because .equals looking for entire String not regular expression
complete code
Scanner scan = new Scanner(System.in);
System.out.println("enter your operation");
String input = scan.next();
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
double answer;
String operator = input.toCharArray()[token[0].length()]+"";
if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {
System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
output>>
for input "2+3" > Operation is +, numbers are 2 and 3
for input "24+45" > Operation is +, numbers are 24 and 45
for input "2++4" > Your entry of 2++4 is invalid

the code may be like this
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
String operator = input.substring(token[0].length,token[0].length+1)//this is the operator
if (token.length > 1){
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}

Access token after splitting input
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
And
String operator = token[1];//this is the operator
wont work because delimiter wont be there in the String array after splitting.

Related

how to fix cannot resolve symbol and variable never used, errors

I am new to java and this is my first program, I'm very confused with these errors and have looked everywhere for the answer. please help!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter first number");
String str1 = myObj.nextLine();
System.out.println("Enter Operator");
String op = myObj.nextLine();
System.out.println("Enter second number");
String str2 = myObj.nextLine();
int num1 = Integer.parseInt(str1);
int num2 = Integer.parseInt(str2);
if (op.equals("+")) {
int ans = (num1 + num2);
} else if (op.equals("-")){
int ans = (num1 - num2);
}
System.out.println(num1 + " " + op + " " + num2 + " = " + ans);
}
}
Then it gives me these errors, I'm using IntelliJ idea
Cannot resolve symbol 'ans'
Variable 'ans' is never used
Variable 'ans' is never used
Cannot resolve symbol 'ans'
Declare ans outside the if:
int ans = 0;
if (op.equals("+")) {
ans = (num1 + num2);
} else if (op.equals("-")){
ans = (num1 - num2);
}
System.out.println(num1 + " " + op + " " + num2 + " = " + ans);
otherwise it is never visible in the line where it is used in System.out.println
Variable 'ans' is never used
Variable 'ans' is never used
In your code ans is declared in the if - code blocks, and after assignment those ans are no longer used, because code-block in if ends just after the assignment.

Evaluating math expressions in a string using regex to split the string

I need some with evaluating math expressions in a string.
As of now my code will work for only positive numbers.
I used regex to split the string into two separate arrays. I was able to split all the math signs in one array and all the numbers in the other. But I am unsure how to do it for negative numbers. (I dont understand the regex i just put stuff and it worked but not for negative numbers)
Anyways here is my code, Thanks in advance!`
boolean mybool = true;
String str = "1.0+2.0+3.0+4.0";
String[] numarray = str.split("[-+/%*]");
String[] signarray = str.split("[0123456789.]");
double result = 0.0;
double num1 = 0.0;
double num2 = 0.0;
String mystr = "";
//Adds each element in sign array to mystr
for(String e : signarray){
if(e != ""){
mystr+=e;
}
}
//Assign signarray new size of length mystr
signarray = new String[mystr.length()];
//Cycle through each element in str and add it to signarray
for(int i = 0; i < mystr.length(); i++){
signarray[i] = mystr.charAt(i)+"";
}
//Print each element in num array
System.out.print("Print each element in number array: ");
for(String e : numarray){
System.out.print(e+ " ");
}
System.out.println();
System.out.print("Print each element in sign array: ");
//print each element in sign array
for(String e : signarray){
System.out.print(e+ " ");
}
System.out.println();
//Prints each element in sign array and element value
for(int i = 0; i < signarray.length; i++){
System.out.println("SignArray[" + i + "] = " + signarray[i]);
}
for(int i = 2; i <= numarray.length; i++){
//this will get the first two indexes of number array
//and store them in num1 and num1 then i use another if
//statement to go sign array to get a sign to evaluate the
//two nums and store the value in result.
//hopefully you understand my logic
if(mybool == true){
num1 = Double.parseDouble(numarray[0]);
num2 = Double.parseDouble(numarray[1]);
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
if(signarray[0].equals("+")){
result = num1 + num2;
System.out.println("Result = num1 + num2 = " + num1 + "+" + num2 + "= " + result );
} else if(signarray[0].equals("-")){
result = num1 - num2;
System.out.println("Result = num1 - num2 = " + num1 + "-" + num2 + "= " + result );
} else if(signarray[0].equals("/")){
result = num1 / num2;
System.out.println("Result = num1 / num2 = " + num1 + "/" + num2 + "= " + result );
} else if(signarray[0].equals("*")){
result = num1 * num2;
System.out.println("Result = num1 * num2 = " + num1 + "*" + num2 + "= " + result );
} else if(signarray[0].equals("%")){
result = num1 % num2;
System.out.println("Result = num1 % num2 = " + num1 + "%" + num2 + "= " + result );
}
mybool = false;
} else {
num2 = Double.parseDouble(numarray[i-1]);
System.out.println("Num2 = " + num2);
if(signarray[i-2].equals("+")){
result = result + num2;
System.out.println("Result after math is : " + result);
} else if(signarray[i-2].equals("-")){
result = result - num2;
System.out.println("Result after math is : " + result);
} else if(signarray[i-2].equals("/")){
result = result / num2;
System.out.println("Result after math is : " + result);
} else if(signarray[i-2].equals("*")){
result = result * num2;
System.out.println("Result after math is : " + result);
} else if(signarray[i-2].equals("%")){
result = result % num2;
System.out.println("Result after math is : " + result);
}
}
}`
Output:
Print each element in number array: 1.0 2.0 3.0 4.0
Print each element in sign array: + + +
SignArray[0] = +
SignArray[1] = +
SignArray[2] = +
num1 = 1.0
num2 = 2.0
Result = num1 + num2 = 1.0+2.0= 3.0
Num2 = 3.0
Result after math is : 6.0
Num2 = 4.0
Result after math is : 10.0
eventually i wanna be able to evaluate a string like this
//String str = "3.01+2.2/4.01*7.1%4.0--2.0";
but i dont know how to get negative numbers from sting and store in the num array.
Thanks for you help!
Ideally, you should use a parser instead of regex. However given your current requirements, it would be simple to use positive and negative lookbehinds.
(1). Operators are always preceded by a decimal number. So we split the arguments by matching any operator which appears after a decimal number (positive lookbehind).
String[] arguments = str.split("(?<=\\d)[-+/%*]");
(2). Arguments may start with an optional minus sign but are never preceded by another decimal number. So we split the operators by matching arguments not after a decimal number (negative lookbehind).
String[] operators = str.split("(?<!\\d)-?[0-9.]+");
Note however that there will be an empty operator at position 0 of the array. If you want to avoid this then there are many different methods you could use instead of String.split.

String output to display message to user

When using my code I am receiving an output message stating that each number that I have entered is prime, even if it is not a prime number. How can I change my output message to reflect the correct is or is not prime result? Here is my code:
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (BigInteger(input) ? " " : " not ") + "a prime number: " + BigInteger(input);
JOptionPane.showMessageDialog (null, output);
}
public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
I think you're having an issue here -
String output = number + " is"
+ (BigInteger(input) ? " " : " not ") + "a prime number: "
+ BigInteger(input);
And you want something more like this -
String output = num + " is"
+ (IsPrime(num) ? " " : " not ") + "a prime number.";
I tested your IsPrime function, and it correctly identified 5 as prime and 4 as not prime. You should probably rename it isPrime to be inline with Java naming conventions.
EDIT
public static void main(String[] args) {
// prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
// display message to user of their results
BigInteger num = new BigInteger(input);
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
JOptionPane.showMessageDialog(null, output);
}
I guess you simply was wrong in the main code; try with this one;
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (IsPrime(num) ? " " : " not ") + "a prime number: " + number;
JOptionPane.showMessageDialog (null, output);
}
Angelo

Simple Calculator Operation

I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...

How to use the while loop and how to use the count in the loop

This program is designed to add 2 random numbers generated by the computer, when the user answer goes wrong , the computer tells the user to try it again, by using the while loop. The program will stop once the user enters a correct number. I have to calculate the wrong count in the while loop, however, it gives me the wrong count 1 when it is the second attempt.Please be kind enough to tell me where I go wrong in the code. Thank you.
import java.util.Scanner;
public class add {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = (int) (Math.random() * 10);
int num2 = (int) (Math.random() * 10);
int wrong = 0;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
System.out.println("The number of attemt is " + wrong);
++wrong;
}
System.out.println("You got it correct !");
}
}
The error is in incrementing the number the user has gotten wrong AFTER printing "You got x wrong"
Just put ++wrong above System.out.println("The number of attemt is " + wrong);
while (num1 + num2 != answer) {
System.out.println("Wrong answer, Try again . " +
"What is " + num1 + "+" + num2 + "? ");
answer = input.nextInt();
++wrong;
System.out.println("The number of attemt is " + wrong);
}
Just change
wrong = 0
to
wrong = 1
wrong should probably be renamed to numberOfAttempts.
Initialize wrong to 1 instead of 0.
int wrong = 1;
A more appropriate name for the variable would be attempt if you take this approach.
You need to increment wrong before you display it:
import java.util.Scanner;
public class Add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
int num1 = (int)(Math.random() * 10);
int num2 = (int)(Math.random() * 10);
int wrong = 0 ;
System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
int answer = input.nextInt();
while (num1 + num2 != answer){
wrong++ ;
System.out.println("Wrong answer, Try again . What is " + num1 +"+"+ num2 + "? " );
answer = input.nextInt();
System.out.println("The number of attempt is " + wrong);
}
System.out.println("You got it correct !");
}
}

Categories