I am trying to create a text based calculator. I have a main class and a calc class. The calc class is where everything will happen, and it will be called in the main class. My problem is several variables in my calc class. It is easier to see in code.
import java.util.Scanner;
public class Calc {
String op;
public void operation(String opt){
System.out.println("What operation would you like to perform?");
Scanner operation = new Scanner(System.in);
op = opt;
String op = operation.toString();
getOp(op);
}
public String getOp(String op){
return op;
}
And later on in my code.
public void calculate(){
operation(op);
getNums(1,2);
if(op == "Division"+"division"+"/"){
double value = 1/2;
System.out.println("Your answer is"+value);
}
if(op == "Multiplication"+"multiplication"+"*"){
double value = 1*2;
System.out.println("Your answer is"+value);
}
if(op == "Addition"+"addition"+"+"){
double value = 1+2;
System.out.println("Your answer is"+value);
}
if(op == "Subtraction"+"subtraction"+"-"){
double value = 1/2;
System.out.println("Your answer is"+value);
}
}
My problem is that I can't seem to set the value of op with the scanner, and I don't know if the value of my numbers (1 and 2) have been set either. Any help is greatly appreciated, thank you.
FWIW, I would use .nextInt instead of .toString. This would ensure it took in a number and then pass it into your store for conditional to take place.
Plus, I think you would be better off using a switch statement on the calculations, in which case you could leave it as .toString or change it to .next and pass in the char or string.
I think like βнɛƨн Ǥʋяʋиɢ's suggestion, you should not call the operation() in your Cal class. if it just prompts user and takes input, it should be in main class.
As i don't see the error message so i guess one of the problem you can get is you declare your op variable one and initiate another local variable op in your operate() function to catch the user's input.
Another thing is shouldn't your Scanner object call the method nextLine() instead of toString() to catch the user's input. I don't have my comp with me so can't post any code but maybe you can try to modify your code first and post some error message to be clearer.
Related
I am creating a class to use which handles user input. This is so that in other projects I can call methods from the class without having to worry about creating scanners in every new project.
There will be a separate method within the class to handle different variable types (float, int, String etc..). I have started with the float type:
import java.util.Scanner;
public class Input {
public static float floatInput() {
Scanner in1 = new Scanner(System.in);
float in;
if (in1.hasNextFloat()) {
in = in1.nextFloat();
return in;
} else {
System.out.print("Incorrect input type, try again");
floatInput();
return 0;
}
}
This method works just fine, except that it must return a float in the else part. In this instance it is a zero, so when inputting to a calculator (for example), the zero causes any output to equal zero.
Is there a way of returning an 'empty' float value to overcome this problem?
Does anybody have any better suggestions for handling incorrect scanner input in general?
Thank you.
You can just read your input as a String and check if it is a float value, else loop until it is or the user gets tired:
public static float floatInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a float:");
for(;;){
try{
return Float.parseFloat(scanner.next());
} catch(NumberFormatException e){
System.out.println("Incorrect input type, try again:");
}
}
}
There is no such thing as an 'empty' float. A float that has not been initialized defaults to 0.0f. If you were to return your 'in' variable, instead of just returning 0 in your else statement it would return 0.0.
Click here to learn more about default values for primitive data types in Java.
public static float floatInput() {
Scanner in1 = new Scanner(System.in);
float in = in1.nextFloat();
while (/*in.isGood()*/) {
System.out.println("Incorrect input type, try again:");
in = in1.nextFloat();
}
return in;
}
This will prevent to call recursivelly while you still haveing instances of the method running on the background with open Scanners waiting for the return.
Also, you can be sure that the output will have nextFloat.
But you need to find a better way of checking if the float is correct such as a try catch block with a parse inside. hasNextFloat() won't tell you.
Trying to test my java "skills" and make a text based game--except i can't get the user input. i already importd the scanner class, and it works well w/ integers so idk what the problem is quite frankly. whenever i try to compile it, the lines containing "String name = scanner.next();" show up with a 'Scanner cannot be resolved' error.
import java.util.Scanner;
public class CH1 {
public static void main (String args[]) {
Scanner s= new Scanner( System.in);
int answer;
System.out.println ("You're in grave danger, but first, I must know your name. Will you tell me? ");
answer = s.nextInt();
if (answer == 1) {
System.out.println ("I respect your decision, but I'll need to know your name
if you turn up dead, unless you want to have a one man funeral.");
System.out.println ("What's your name?");
String name = scanner.next();
}
else if (answer == 2) {
System.out.println("Great, now what's your name?");
String name = scanner.next();
}
else {
System.out.println(" Huh? I didn't really get that. (1 for no, 2 for yes.)");
}
}
}
You named that scanner s first!
You can't just use a different name later on!
So simply change the scanner variable name to "scanner" and keep using that name.
Beyond that: Single character variable names are something you almost never do (except for index values in for loops). The point is: variable names should say something about the thing they denote. "s" says nothing!
I need to check a user is inputting a numeric value in java. I've been trying to use the hasNextDouble but am getting weird errors using the hasNextDouble method and am not certain this is the way to perform this check.
Please note I cannot use while loops or any other advanced method except if.
import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
public static void main (String [] args)
{
final int MAX=100, feet=12, meter=100;
final double inch=2.54;
Scanner scan = new Scanner (System.in);
System.out.println ("This program converts distances. ");
System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
double distance=scan.nextDouble();
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
distance=scan.nextDouble();
}
int unitType = scan.nextInt();
if (distance<0)
{
System.out.println ("Please enter a non negative distance");
}
....
I fixed the typo but its still not functioning, when I input for example "a" it crashes. To me it also doesnt make sense to call hasNextDouble after placing the value in the 'double distance' variable but I didn't find any other way yet.
I only have 1 double variable to check, the 'int' does not need validation.
EDIT:
I advance a bit. Now it displays the error before crashing. How do I make it not crash but take the variable again?
if(!scan.hasNextDouble())
System.out.println ("please enter a numeric value");
distance=scan.nextDouble();
Thank you!
Typos aside, you're invoking hasNextDouble after consuming nextDouble.
The easiest way to fetch both in one line is to:
if (scan.hasNextDouble()) {
// TODO something
double foo = scan.nextDouble(); // this consumes the first double
}
else { // TODO exit with error }
if (scan.hasNextDouble()) {
// TODO something else
double bar = scan.nextDouble(); // this consumes the second double
}
else { // TODO exit with error }
If you want it in two gos (i.e. user presses enter twice) you can consume scan.next() twice and use Double.parseDouble on both String, while catching a NumberFormatException for format errors.
It should be scan.hasNextDouble() with emphasis on Double.
This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}
For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}
Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.
You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.
package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards
I am learning JAVA and trying to write my first loop. The loop should prompt the user to guess a defined name.
The code is not performing right. I have tried to search for help on different JAVA tuturials both not found any examples where you guess a name/string but a lot where you should guess a number.
This is my code:
/**
*
* #author mso_
*/
import java.util.Scanner;
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
String guessName = guess.next(); <-- ERROR
//Create loop
} while (guessName != name); <-- ERROR
System.out.println("Sorry, wrong guess, please enter another guess: ");
if (guessName = name); <-- ERROR
System.out.println("Right on! ");
}
}
What have I done wrong?
String comparison
You can't compare Strings like this. This will only compare the references. You must use the equals() method :
while (! guessName.equals(name));
A little explanation : http://www.zparacha.com/java-string-comparison/
Variable redeclaration
There is another error in your code, you try to redeclare guessName inside the loop. You must declare guessName only once outside of the loop (ie before the do {).
General mistakes
Thirdly, there's a some other errors in your code. I think all of them were pointed out in the others answer, but I'll do a quick list :
if (guessName = name); This is a useless statement as is, you must open a block : if(condition) { statement; }
Same line, your doing an assignment, not a comparison, and like said, with String you must use .equals()
The System.out.println() won't be executed when you think. Re-read the doc about do { } while() loop until you really understand them.
My advise : read carefully the error message of your compiler and read some doc before writing code.
What errors?
Use .equals when comparing strings
You are using the assignment operator and not the equivalence operator at
if (guessName = name)
you need to do
if(guessName.equals(name)) instead.
You're comparing references (well, with guessName = name, you're actually assigning a value to guessName). Use String.equals() instead of == and !=.
you are comparing two objects. Not two string values.
use equals
That won't compile for a start - you declare String guessName on the third line of the main method, and then declare the same variable again within the do loop. You should simply use the name of the variable to assign to it:
guessName = guess.next();
Because of this error, presumably your IDE's compiler doesn't see the variable at all, so the subsequent lines that refer to guessName are also flagged as errors. Fixing this first line should clear those up, unless there's another problem lying there that I've missed.
Among other things there is a wrong semicolon after the if:
if (name.equals(guessName)) //removed the semicolon and use .equals
System.out.println("Right on! ");
and it's an assignment instead of a comparison as other answers state by now.
Try this
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName = null;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.nextLine(); <-- ERROR
if(!guessName.equals(name))
{
System.out.println("Sorry, wrong guess, please enter another guess: ");
}
//Create loop
} while (!guessName.equals(name)); <-- ERROR
if (guessName.equals(name)) <-- ERROR
System.out.println("Right on! ");
}
}
The line String guessName = guess.next(); needs to be changed to:
guessName = guess.next();
Because "guessName" is already defined earlier.
Additionally, when you compare strings you need to use the method equals and not the operator ==. So } while (guessName != name); should be:
} while (!guessName.equals(name));
And if (guessName = name); should be changed to:
if (guessName.equals(name))
Here is what the javac compiler says:
GuessName.java:26: guessName is already defined in main(java.lang.String[])
String guessName = guess.next(); //<-- ERROR
^
GuessName.java:32: incompatible types
found : java.lang.String
required: boolean
if (guessName = name);// <-- ERROR
^
2 errors
For the first one, you should not declare another local variable: drop the String. For the second, use .equals to compare String objects, as the doc says.
You will obtain something like that:
...
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.next(); //<-- FIXED
//Create loop
} while (!guessName.equals(name)) //<-- FIXED
if (guessName.equals(name))// <-- FIXED
System.out.println("Right on! ");
}
...
which works correctly.
The strings must be compared using the equals method.