How to start debugging this Java code? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm very new at programming, and I have no idea why this doesn't work.
What I want to do is like:
pmmd = plus - minus - multi.. - divide..
code:
import java.util.Scanner;
class MyCalculator{
public static void main(String args[]){
Scanner ScanN = new Scanner(System.in);
Scanner ScanT = new Scanner(System.in);
Double fnum, snum, answer;
Boolean pmmd;
System.out.println("Enter First Number");
fnum = ScanN.nextDouble();
System.out.println("Enter Second Number");
snum = ScanN.nextDouble();
System.out.println("Enter minus, plus, multi or divide");
pmmd = ScanT.nextBoolean();
Object plus = "+";
Object minus = "-";
Object multi = "*";
if(pmmd.equals(plus)) {
answer = fnum + snum;
}
else if(pmmd.equals(minus)) {
answer = fnum - snum;
}
else if(pmmd.equals(multi)) {
answer = fnum * snum;
}
else {
answer = fnum / snum;
}
System.out.println(answer);
}
}

Here:
System.out.println("Enter minus, plus, multi or divide");
pmmd = ScanT.nextBoolean();
A boolean is about true/false. But "+" is a string, not a true/false value!
You want a String, like
String operator = scanT.next();
Beyond that, there are many other things that don't make much sense in your code. For example this:
Object plus = "+";
should be
String plus = "+";
for example.
And you would rather do something like:
switch(operatorGivenByUser) {
case "+":
...
instead of putting up such an if/else chain.
I know, it seems hard, but the point is: when you write code, be sure to understand what each line is doing. If you don't understand it - read about it.
Beyond that, there are more subtle problems like:
Bad naming: "pmmd" says nothing about the intent of that variable. I renamed it to "operator"; or "operatorGivenByUser" - which gives you at least a hint what the content of that variable is about!
Bad naming (II): you should read about java coding style conventions. Variable names start lowercase; so it is scanT ; not ScanT. (where again; that name actually says nothing, just call it scanner for example)
Insufficient checking: when doing divisions, make sure that the denominator is not 0.

Related

Want to programm calculator, want to change String into real operator

I want to code a simple calculator and already got some code. But now I want to change the String I got there into an Operator. For example:
My input is: "1,5 - 1,1 + 3,2 ="
Now I have a double array and a String array.
So after that I want to put it together, so it calculates this complete task.
double result = double[0] String[0] double[1] ....
I hope you can help there, and I apologize for my grammar etc., english is not my main language.
import java.util.*;
public class calculator
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
double[] zahl;
zahl = new double[10];
double ergebnis;
String[] zeichen;
zeichen = new String[10];
Scanner input = new Scanner (System.in);
while (input.hasNext())
{
if (input.hasNextDouble())
{
zahl[a] = input.nextDouble();
a++;
}
else if (input.hasNext())
{
zeichen[b] = input.next();
if (zeichen.equals ("=")) break;
b++;
}
}
input.close();
}
}
If I type in: "1,5 + 2,3 * 4,2 =" I want to get the result with point before line and without .math
What you want to do is parse a single String and convert it into a mathematical expression, which you then want to resolve and output the result. For that, you need to define a "language" and effectively write an interpreter. This is not trivial, specifically if you want to expand your syntax with bracketing and thelike.
The primary question you have to answer is, whether you want to use a solution (because you are not the first person to attempt this) or if you want to actually write this yourself.
There are "simple" solutions, for example, you could instantiate a javascript engine in Java and input your string, but that would allow much more, and maybe even things you don't want. Or you could use a library which already does this. This Thread already answered a similar question with multiple interesting answers:
How to evaluate a math expression given in string form?
Otherwise, you might be in for a surprise, concerning the amount of work, you are getting yourself into. :)

Can someone explain this if statement that I have going and tell me what is wrong?

I am a beginner to programming (literally two days new), and I am having an issue. I am trying to make a VERY basic calculator, where the user inputs the first number, the operation (only +, -, *, and /), and then the second number. I'm having trouble getting the input of the operation to determine what the answer will be with the if statements, so can someone please explain it using very simple terminology?
package learn;
import java.util.Scanner;
class calculator{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
double termOne, operation, termTwo, answer;
System.out.println("Enter first term: ");
termOne = input.nextDouble();
System.out.println("Enter operation (Valid operations are : ");
operation = input.nextDouble();
System.out.println("Etner second term: ");
termTwo = input.nextDouble();
if (operation == add) {
answer = termOne + termTwo;
System.out.println(answer);
} else if (operation == subtract) {
answer = termOne - termTwo;
System.out.println(answer);
} else if (operation == divide) {
answer = termOne / termTwo;
System.out.println(answer);
} else (operation == multiply) {
answer = termOne * termTwo;
System.out.println(answer);
}
}
}
Okay so both Tunaki and Pshemo are right but I will try to point out your problems on a more simplified level.
Your first mistake is the way you declare your variable "operation". You use the datatype double (which is for floating point numbers, kinda) but later want it to hold a string.
Secondly, I'm assuming you are checking if the user typed in "add" to then add the two numbers. However there are several problems here:
You are not using quotes for your string so Java is looking for a variable called add rather than the actual "add".
String comparison in java does (mostly) not work this way. A better way to compare two strings is to use String.equals("otherString"). In your example that would be if(operation.equals("add"))
I hope this helps... Oh and I welcome anyone to format my post, I'm on a mobile and it's a pain in the a**

trying to add more ints to one main one [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i'm trying to make a questions game to try my knowledge and abilities
anyway i'm trying to use an integer to be the points and every question the user
answer gets a special amount of points anyway i was trying to do like this
switch (Ques){ case 1 : //first question about India and where it is in the map
System.out.println("in what continent India is?");
Scanner IndiaAns = new Scanner(System.in); //Scanner to receive user answer
String IndiaAns2 , IndiaAnswer ; //strings to be used to receive user input and matching with the correct ones
IndiaAns2 = IndiaAns.nextLine(); //Scanner will work here and receive...
IndiaAnswer = "asia"; //the correct answer here and will be matched with user ones
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
case 2:
System.out.println("the Appstore founds in any phone model?");
Scanner Appstore =new Scanner(System.in);
String AppstoreAns1 ,AppstoreAns2; //strings saving
AppstoreAns1 = Appstore.nextLine(); //Scanner
AppstoreAns2 = "iphone"; //matching with user answer
if (AppstoreAns1 == AppstoreAns2)
{ int Threepoints = 3; Points = +Threepoints;} else { Points = +0;}
.. there's two other case and the points integer is in not in the code sample area is in upper line any ways if the full codes its necessary i'll put it
About your code ,
if (IndiaAns2 == IndiaAnswer)
{int Twopoints = 2; Points = + Twopoints; } else{}
Should be something like
if(indiaAns2.equals(indiaAnswer)){
points += QUESTION_1_POINTS;
}
Where QUESTION_1_POINTS is defined as a constant like `
public static final int QUESTION_1_POINTS =2;
There you are assigning to points variable , points + QUESTION_1_POINTS.
points += someInteger --> points = points + someInteger
Some advices,
1) Follow Java Code Conventions , variable names start with lower-case
2) For object comparision always use equals() instead of ==
Example:
Change
if (IndiaAns2 == IndiaAnswer)
to:
if (indiaAns2.equals(indiaAnswer))
3) You need to make switch statement
switch(condition){
case 1:
//code
break;
case 2:
//code
break;
default:// some code;
}

How to use the value of variable from if/else tree as value of variable for a while loop afterwards

Here is my program code as I have it written so far. It's saying I haven't initialized answer. I want to use the value of answer after the if/else tree executes to convert the number into asterisks.
import java.io.*;
import java.util.*;
public class Project5 {
public static void main(String[] args){
System.out.println("Please enter a formula of this form:operator,operand,operand(ex. add,2,2):");
// wanted to change things but was not sure how far I was allowed to go so I used commas instead of spaces
//was trying to split with a delimiter but kept getting an error [Ljava.lang.String;#55e83f9
Scanner input = new Scanner(System.in);
String formula = input.nextLine();
System.out.println(formula);
String oper = formula.substring(0,3);
System.out.println(oper);
String fnum = formula.substring(4,5);
System.out.println(fnum);
String snum = formula.substring(6,7);
System.out.println(snum);
double freal = Integer.parseInt(fnum);
System.out.println(freal);
double sreal = Integer.parseInt(snum);
double answer;
if (oper.equalsIgnoreCase("add") == true){
answer = freal+sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("subtract") == true){
answer = freal-sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("multiply") == true){
answer = freal*sreal;
System.out.println(answer);
}
else if(oper.equalsIgnoreCase("divide") == true){
answer = freal/sreal;
System.out.println(answer);
}
else
System.out.println("not valid.");
while(answer > 0){
System.out.print("*");
answer--;
}
}}
Because in the final else branch, you don't assign a value to answer. If that is the tree that's executed, then when you get to the while loop, it will be undefined. You can fix this by initially initializing answer to some value or by making sure every branch of the if/else tree assigns answer a value.
Edit To address your question, change
double answer;
To
double answer = 0.0;
That will fix the problem.
The wording of the error you are getting is a good start in working out what the problem is:
Project5.java:41: variable answer might not have been initialized
So you should initialize the variable answer
Edit: To be even clearer, change the line that says double answer; to double answer = 0.0; thereby initializing the answer variable. That is what the compiler is complaining about and is the only change you need to make in order for the code to compile and execute. By the way, you will have more errors to deal with after this because although you are allowing the operator to be 3 characters, you are trying to compare this with a longer word in some cases. So add works but subtract does not.
I think the only thing is that you have to initialize answer: double answer = 0.0;

how to create a counter in a dr Java program

/*This is a quiz program that will ask the user 10 questions. the user will answer
* these questions and will be scored out of 10.*/
class Quiz {
public static void main(String args[]) {
// Instructions
System.out.println("instructions");
System.out.println(" ");
System.out
.println("1. You wll be asked ten questions through out the quiz.");
System.out
.println("2. The first question will appear, you will have to answer that question for the next question to appear.");
System.out
.println("3. When you answer the last question you will be told your score.");
System.out.println(" ");
System.out.println("welcome to the basketball quiz.");
// question 1
System.out.println(" ");
System.out.println("Question 1. ");
System.out.println("How tall is a basketball hoop? ");
System.out.println("Type in Answer here:");
String Question1 = In.getString();
if (Question1.equalsIgnoreCase("10 Feet")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
// question 2
System.out.println(" ");
System.out.println("Question 2. ");
System.out.println("Who invented basketball? ");
System.out.println("Type in Answer here:");
String Question2 = In.getString();
if (Question2.equalsIgnoreCase("James Naismith ")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
}
}
This is my program that I am writing. I want to make a counter that will keep score of every question that is answered right and then display it to the user after the questions are finished. I tried using this:
int score=0;
score=score+1;
It doesn't not work for the 2nd question, but works for the 3rd... it gives me an error.
Is there another way I can do this or am I doing something wrong?
It looks like you are on the right track. You need to declare a socre variable at the begiunning of the program.
int score = 0;
Then in each question where you print out "correct" you can increment the score like this:
score++;
At the end of the program after the last question you can print the score.
Maybe you should post the error you got when you tried it.
UPDATE:
The syntax is score++ NOT score=++. That is, take out the = sign.
What you did is correct. Heed the comment on your post; you need semi-colons at the end of your posted solution. Also, per the Java Language Specification, it's best to name your variable with all lower case characters:
int score = 0;
// question code
score += 1;
or
score = score + 1;
or
score++;
You need to place the variable declaration (int score = 0;) outside of any loops (your if/else loops). It would be best to place it at the first line of the main method.
Your problem is possible because you have a whitespace character after the name "James Naismith" in the comparison for their given answer. For it to be evaluated to true the user must answer with the exact string "James Naismith " instead of "James Naismith"
Edit: Nevermind, This should not cause an error but it is something to bring your attention to still because it could affect the result of the program.

Categories

Resources