This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.
Related
The code below is for a simple calculator with the four basic mathematical operators. It is a working program, it works as expected. However, I have a few questions to understand and improve both my program as well as my understanding of Java. (I have used google but the amount of redundant info confuses me and haven't found any perfect answers on StackOverflow too, though there are dozens of related questions. Believe me, I did tried before posting here).
How can I make sure that the user input is exactly and strictly one char?
here in my program, it accepts more than one character (+-*) but operates on the first char (+) only. I want to make sure more than one character is not accepted as input.
After successful execution of the program, how can I somehow let the user repeat the main method? I mean, a user adds two numbers, gets his answer and he wants to do another calculation, maybe multiply two numbers this time. I can ask the user for yes or no to continue but how do I take him/her back to the beginning? (will a loop work? how?)
A the end of the program I used two methods to output a message. The system.out.print works fine but the JOptionPane method doesn't display the message and the program doesn't terminate (I have commented it out). I would like to understand why?
Is the default case required in the switch? And Am I following the correct code structure? (the arrangements and uses of curly braces)
NB: As I said this calculator works fine and can be used by newbies like myself to better understand the concept as I have commented on every detail. Please understand that I couldn't add everything in the question title due to limits...
package mycalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator//
// Variable type declarations//
char OP;
int firstNum;
int secNum;
// Display an explanation of what this program does//
System.out.println("This is a simple calculator that will do basic
calculations such as :"
+ "\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.//
Scanner input = new Scanner(System.in);
// Ask user to input any positive number and read it//
System.out.println("Enter Any positive number followed by pressing
ENTER.");
firstNum = input.nextInt();
// Ask user to input/decide his choice operator and read it //
System.out.println("Enter a valid OPERATOR sign followed by pressing
ENTER.");
OP = input.next().charAt(0);
// Loop the below statement till one of the four (+,-,*,/) is entered.//
while(OP != '+' && OP != '-' && OP != '*' && OP != '/'){
System.out.println("Please Re-enter a valid Operator (+,-*,/)");
OP = input.next().charAt(0);}
// Ask user for any second number and read it//
System.out.println("Enter your Second number followed by an ENTER
stroke.");
secNum = input.nextInt();
// Various possible Resolution based on OP value.//
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing Results based on OP and display.//
switch(OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+
DPro);
break;
//Maybe the default case is actually not needed but is added for totality//
default : System.out.println("Try Again");
break;
}
// The following code maybe deleted, it is for experimental purpose//
// Just checking if additional statements executes after a program
completes//
System.out.println("Test Message ");
// JOptionPane.showMessageDialog(null, "The Process Ends Here!");
//The test message works fine//
//The JOptionPane statement don't work and program doesn't end. WHY?//
}
}
How can I make sure that the user input is exactly and strictly one
char? here in my program, it accepts more than one character (+-*) but
operates on the first char (+) only. I want to make sure more than one
character is not accepted as input.
If you use console application and Scanner, only thing that you can do is read a String and check its length. In case you use Swing, you could implement KeyPressListener and proceed exactly after user press a button (but not for console application).
After successful execution of the program, how can I somehow let the
user repeat the main method? I mean, a user adds two numbers, gets his
answer and he wants to do another calculation, maybe multiply two
numbers this time. I can ask the user for yes or no to continue but
how do I take him/her back to the beginning? (will a loop work? how?)
You can't repeat main method. In Java main method is been executing only once. To repeate your code, you could wrap whole main method content to the infinite loop or move the content to the separate method and call it from the loop in the main method.
A the end of the program I used two methods to output a message. The
system.out.print works fine but the JOptionPane method doesn't display
the message and the program doesn't terminate (I have commented it
out). I would like to understand why?
JOptionPane works only for graphic application (Swing/AWT). This is not available in console. You have only standard input and output there.
Is the default case required in the switch? And Am I following the
correct code structure? (the arrangements and uses of curly braces)
No, default case is optional by JVM syntax. I remember, that e.g. in C++ there was reccomendation to place it (event empty), to exclude side effects of compilators. I do not know, is there such reccomendation in Java, but when I use switch, I prefer to always add it to exclude logical problem (but this is definetly optional according to syntax case). You use switch correctly.
public static void main(String[] args) {
System.out.println("This is a simple calculator that will do basic calculations such as :"
+ "\nAddition (+)"
+ "\nMultiplication (*)"
+ "\nSubtraction (-)"
+ "\nDivision (/)");
System.out.println();
try (Scanner scan = new Scanner(System.in)) {
while (true) {
System.out.println("Enter Any positive number followed by pressing ENTER.");
int first = scan.nextInt();
System.out.println("Enter a valid OPERATOR (+,*,-,/) sign followed by pressing ENTER.");
String operator = scan.next();
while (operator.length() != 1 || !"+*-/".contains(operator)) {
System.out.println("Please Re-enter a valid Operator (+,-*,/)");
operator = scan.next();
}
scan.nextLine();
System.out.println("Enter your Second number followed by an ENTER stroke.");
int second = scan.nextInt();
if ("+".equals(operator))
System.out.println("The Resulting sum is " + (first + second));
else if ("*".equals(operator))
System.out.println("The Resulting mul is " + (first * second));
else if ("-".equals(operator))
System.out.println("The Resulting sub is " + (first - second));
else if ("/".equals(operator))
System.out.println("The Resulting div is " + ((double)first / second));
System.out.println();
System.out.println("Do you want to exit ('y' to exit)?");
if ("y".equals(scan.next()))
return;
System.out.println();
}
}
}
1) you can check size of string input.next() .If it is one then continue else again prompt for operator choice .
2)I would suggest better create a different method and put all logic in it and call it the number of time you want or call infinite number of times.
4)Should switch statements always contain a default clause?
I am programing in java and have also very little programming experience.
I am trying to make a program there you first write in a number of integers in a scanner. In the next window you are supposed to write only one integer and that integer the program will search for and tell if it is or isn't in the "Scanner numbers"
My problem is that when i for example write 1 2 3 and in the next window write 2 it doesn't recognize there is a 2 in the scanner but if I instead write a 1 it works nicely.
Heres the code:
public class Inlämningsuppgift_kap9 {
public static void main(String[] args) {
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
Scanner sc1 = new Scanner(s1);
String s2 = JOptionPane.showInputDialog(
"Chose a integer that the program will search for!"
);
int a = Integer.parseInt(s2);
while(sc1.hasNextInt()){
if(a == sc1.nextInt()){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
else {
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
}
}
}
}
Thanks for any help!
Not going to do your homework for you, but a hint there: it is not a good idea to mix Swing UIs and a scanner that reads from stdin.
In other words: either use a graphical UI for all input/output; or just read/write from/to stdin (using out.println and that scanner code).
And then: assuming that the user first enters a string such as "1 2 3 4 5"; you need some further processing. You have to split that string (for example on spaces); and then turn each of that substrings ... into a real number. As your next step is to ask the user to input a number. And when you want to know if one number is in a list of other numbers, then you need to turn your initial string into that list of numbers!
So, you want to study javadoc for:
String.split()
Integer.parseInt()
you should not parse the input. makes it much easier to do what you want.
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
String s2 = JOptionPane.showInputDialog("Chose a integer that the program will search for!");
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
JOptionPane.showMessageDialog(null, "The integer can be found");
System.exit(0);
}
}
JOptionPane.showMessageDialog(null, "The integer cannot be found");
System.exit(0);
i like this solution more since it has less code an still works fine
lets just anylyze your code and hope i'm not mistaken :) , the variables are initialized,then You start a loop with
while(sc1.hasNextInt())
it basically runs for x times where x is the number of inputs (sc1 variable's length) then you test if the number in current iteration is the number you look for. If it's you print success code and close the loop. if it isn't you print failure code and also close the loop. So when you provide 1 as input the execution is fine because 1 is the 1st element but 2 as second argument is never tested because of
System.exit(0);
in else's brackets
I'm trying to learn java but I'm stuck trying to do a single program which concerns Do While Statement with two conditions. Specifically, I want a method to run until the user write "yes" or "no". Well, down there is my thing, what is wrong with it?
String answerString;
Scanner user_input = new Scanner(System.in);
System.out.println("Do you want a cookie? ");
do{
answerString = user_input.next();
if(answerString.equalsIgnoreCase("yes")){
System.out.println("You want a cookie.");
}else if(answerString.equalsIgnoreCase("no")){
System.out.println("You don't want a cookie.");
}else{
System.out.println("Answer by saying 'yes' or 'no'");
}while(user_input == 'yes' || user_input == 'no');
}
}}
I'd do something similar to Tim's answer. But to do things the way you were trying to do them, you have a lot of problems that need to be fixed:
(1) String literals in Java are surrounded by double quote marks, not single quote marks.
(2) user_input is a Scanner. You can't compare a scanner to a string. You can only compare a String to another String. So you should be using answerString in your comparison, not user_input.
(3) Never use == to compare strings. StackOverflow has 953,235 Java questions, and approximately 826,102 of those involve someone trying to use == to compare strings. (OK, that's a slight exaggeration.) Use the equals method: string1.equals(string2).
(4) When you write a do-while loop, the syntax is do, followed by {, followed by the code in the loop, followed by }, followed by while(condition);. It looks like you put the last } in the wrong place. The } just before the while belongs to the else, so that doesn't count; you need another } before while, not after it.
(5) I think you were trying to write a loop that keeps going if the input isn't yes or no. Instead, you did the opposite: you wrote a loop that keeps going as long as the input is yes or no. Your while condition should look something like
while (!(answerString.equals("yes") || answerString.equals("no")));
[Actually, it should be equalsIgnoreCase to be consistent with the rest of the code.] ! means "not" here, and note that I had to put the whole expression in parentheses after the !, otherwise the ! would have applied only to the first part of the expression. If you're trying to write a loop that does "Loop until blah-blah-blah", you have to write it as "Loop while ! (blah-blah-blah)".
I might opt for a do loop which will continue to take in command line user input until he enters a "yes" or "no" answer, at which point the loop breaks.
do {
answerString = user_input.next();
if ("yes".equalsIgnoreCase(answerString)) {
System.out.println("You want a cookie.");
break;
} else if ("no".equalsIgnoreCase(answerString)) {
System.out.println("You don't want a cookie.");
break;
} else {
System.out.println("Answer by saying 'yes' or 'no'");
}
} while(true);
What i'd like to do is that to check if the user input fits and if so then use the user input, otherwise throw exception.
For fit there can only be one true input which is in form of: x,y;x,y;x,y;x,y where x >= 0 & y > 0. (x and y do not have to be same value in every comma separator, for example true input is 0,1;2,3;4,5;6,7) If user types anything else, for example "asd" or 0,1;2,3;4,5 (missing one x,y), he gets the exception. I think i can handle doing the exception throwing but the problem is i don't know how to check if the user input fits. I don't know if it's necessary to provide my code here because the checking part is not in my code yet and anything else is unimportant anyways.
Code was requested, don't know for what reasons but created some for quick example:
TextField tf1 = new TextField();
String inputText = tf1.getText();
if (inputText == form(x,y;x,y;x,y;x,y)) {
// do things;
}
else {
throw exception;
}
From your test case 0,1;2,3;4,5, it is defined that a number of yours ("x") would consist of either zero of a sequence of integers not trended by zero. This would be:
(?:0|[1-9]\d*+)
From there you can quantify a subpattern for repeating the rest of the section "x,y":
(?:0|[1-9]\d*+),[1-9]\d*+(?:;(?:0|[1-9]\d*+),[1-9]\d*+){3}
Here is a regex demo.
Use regexp
if (inputText.matches("[0-9]+,[1-9]+[0-9]*(?:;[0-9]+,[1-9]+[0-9]*){3}"))
{
// do things
}
I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.