Calculator int choice = Integer.parseInt(char_a); java - java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}

I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);

There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

Related

The Equals Function does not Work When it is In While Loop

I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}

I can't seem to figure out how to display answers as words for my Calculator Project?

I have never taken a programming class before so I am very new to all of this and am having a bit of a challenge trying to get my answers to be displayed in writing. For example: if the user enters the numbers 2 and 5 and *, the answer should be displayed as two multiplied by five is 10.
Here is my program:
import java.util.Scanner;
public class CalculatorProjectCH
{//begin class
public static void main(String[] args)
{//begin main
//This program will ask the user to input two digits from 0-9 and then input a method of operation.
System.out.println("This program will act as a simple calculator. ");
System.out.println("It will ask you to enter two numbers from 0-9 and a method of operation "
+"(+, -, *, /, ^.) ");
//Declare variables input1, input2, result1, result2, result3, result4, and result5, as doubles.
double input1, input2, result1, result2, result3, result4, result5;
String text;
//Create scanner object to allow for input
Scanner input = new Scanner (System.in);
//Ask the user to enter the first number
System.out.print("\nEnter your first number: ");
input1 = input. nextDouble();
//Ask the user to enter the operation
System.out.println("Please enter the operation you would like to execute: ");
text = input.next();
//Ask the user to enter the second number
System.out.println("Enter your second number: ");
input2 = input.nextDouble();
result1= input1+input2;
result2= input1-input2;
result3= input1*input2;
result4= input1/input2;
result5= Math.pow(input1,input2);
switch (text)
{
case "+" :
System.out.println(result1);
break;
case "-" :
System.out.println(result2);
break;
case "*" :
System.out.println(result3);
break;
case "/" :
System.out.println(result4);
break;
case "^" :
System.out.println(result5);
break;
//If the user did not enter a valid method of operation
default :
System.out.println("Your operation was not recognized.");
}
}//end main
}//end class
You need to link the int value to the String version of the word somehow. I would suggest using an array:
String[] wordNumbers = new String[]{"zero","one", "two", "three"..."nine"};
Now when you need to print the String version of a number, just do this:
System.out.println(wordNumbers[0]);
Output:
zero
case "*" :
System.out.println(input1 + " multiplied by " + input2 + " is " + result3);
break;
case "/" :
System.out.println(input1 + " devided by " + input2 + " is " + result4);
break;
So I didn't change your code, just added this little part as an example to make sure what your question is about, is this what you are looking for?? And if this is it, you can just add + and - on your own with this principle.
there are another answers in stackoverflow, if you want this in your program than just tell me I can help you make it, I am just not sure what exactly you need
here I found a youtube video if you are into videos

"Must be of an array type but is resolved to string"....Why and how do I fix it?

I'm supposed to create a code that will basically act as a calculator for the operators +,-,*,/, and %. I've posted the code below.
import java.util.Scanner;
public class TestCode {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an operation: ");
String userOperation = input.nextLine();
if (userOperation.length() != 3) {
System.out.println(
"Usage: java Calculator \"operand1 operator operand2\"");
System.exit(0);
}
// The result of the operation
int result = 0;
// Split items from a string
String[] tokens = userOperation[0].split(""); <===== Error line
// Determine the operator
switch (tokens[1].charAt(0)) {
case '+': result = Integer.parseInt(tokens[0]) +
Integer.parseInt(tokens[2]);
break;
case '-': result = Integer.parseInt(tokens[0]) -
Integer.parseInt(tokens[2]);
break;
case '*': result = Integer.parseInt(tokens[0]) *
Integer.parseInt(tokens[2]);
break;
case '/': result = Integer.parseInt(tokens[0]) /
Integer.parseInt(tokens[2]);
}
// Display result
System.out.println(tokens[0] + ' ' + tokens[1] + ' '
+ tokens[2] + " = " + result);
}
}
I've tried pretty much everything that I can think of. What do I need to do to change it, and why is it currently not working? Thank you!!!
userOperation is a String:
String userOperation = input.nextLine();
You later treat it as an array:
userOperation[0]
You can't do that. If you want to grab a specific character from a String in Java, then do the following:
char c = userOperation.charAt(0);
SIDENOTE: I'm not sure what you're exactly doing with this .split("");, but I think you should probably split your String into tokens more carefully (probably via Regex).
Try:
userOperation.split("")
userOperation is a simple String, not an array so you cannot access it with [].

In java, in this program it suddenly stops running properly at a certain point of code? but it compiles? any ideas what could be the issue?

import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.

Looping distance between two points, and q for quit

This is my situation:
i need the code to run in a loop, over and over again asking the same question(s) to the user, until the user types a "q" for any point to terminate/exit the loop, thus exiting the program.
The problem is that i tried to used a do-while/while loop, and those loops executes only if the conditions comes out to be true. But i need the condition ("q") to be false so it can continue the loop. If the condition is true (input.equals("q")) , then it just does not nothing because instead of the integer/double, it will use a string ("q") to calculate the distance.
i have already figured out how to get the distance, the code as is works well, but is there any work-around that i can make the loop continue while the condition is false?
and by the way, i am just barely learning java just in case...
'.
import java.*;
public class Points {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the first X coordinate: ");
double x1 = input.nextDouble();
System.out.print("Enter the first Y coordinate: ");
double y1 = input.nextDouble();
System.out.print("Enter the second X coordinate: ");
double x2 = input.nextDouble();
System.out.print("Enter the second Y coordinate: ");
double y2 = input.nextDouble();
System.out.println("(" + x1 + ", " + y1 + ")" + " " + "(" + x2 + ", " + y2+ ")");
double getSolution = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
System.out.println(getSolution);
}
}'
The solution to this is to use String line = input.nextLine() instead of nextDouble(). Then you can have a method like:
public static boolean timeToExit(String input) {
return input.equalsIgnoreCase("q");
}
This method will need to be called each time the user provides input:
if (timeToExit(line)) break;
That will exit a loop.
Now, since you have a String representation of the double, you will need to use Double.parseDouble(line) to turn the String into a number.
Then all you have to do is enclose everything in an infinite loop -> while(true) { }
And, the only time it will exit the loop is if the timeToExit method returned true, and you break the loop.
This all turns into something like:
while (true) {
...
System.out.print("Enter the first X coordinate: ");
String x1 = input.nextLine();
if (timeToExit(x1)) break;
double x1_d = Double.parseDouble(x1);
...
}
just some pseudocode:
while (! input.equals("q") )
// do something
If the user inputs q, input.equals("q") returns true which is then negated and breaks the loops.
Otherwise, the user inputs another number say 44, input.equals("q") equals false, which is negated and the loop continues.
I don't see a loop in your code... :s
But, why don't you try this:
while(true)
{
string input = // I don't remember the code to create a stream for standard input
if(input == "q"){
break;
}
else{
java.util.Scanner inputWithNumbers = new java.util.Scanner(input);
//---! All math operations here
}
}

Categories