Empty check with parse int - java

A few days ago i posted a topic about if/else and while loops.
I have gotten a bit further and now made a little program to guess a number.
I would like to implement a feature to check if the user has an empty input but i cannot seem to figure it out!
Is there anyone who can help me a bit? Im still a pretty early beginner at JAVA.
Here is my current code:
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author henluu
*/
public class Practice {
public static void main(String[] args) {
//create new scanner
Scanner input = new Scanner(System.in);
int raad = 0;
raad = Integer.parseInt(JOptionPane.showInputDialog("Guess the number"));
while (Practice.rn() != raad) {
JOptionPane.showMessageDialog( null, ("Your number is not the same as the random number"));
raad = Integer.parseInt(JOptionPane.showInputDialog("Guess the number"));
//empty check
if (raad == " ") {
Integer.parseInt(JOptionPane.showInputDialog("No Input"));
}
}
JOptionPane.showMessageDialog( null, ("You guesse dit right! The number was: ") + Practice.rn());
}
//method to generate random number
public static int rn() {
int random = (int) Math.floor((Math.random() * 10) + 1);
return random;
}
}

The point is: that JOptionPane is returning a string to you.
You could do something like:
private int fetchIntFromString(String userInput) {
if (userInput.isEmpty()) {
throw new IllegalArgumentException("input must not be empty");
}
return Integer.parseInt(userInput);
}
to be used like:
try {
raad = fetchIntFromString(JOptionPane.show...
} catch (Exception e) {
... give some error message
In other words: when the user gives a number, it is simply turned into a numeric value and returned. If the user input is empty or can't be parsed as number, an exception is thrown; which needs to be caught within the method that calls fetchIntFromString()

Since you are learning i'm not going show you the standard library solutions, but a solution that is library independant and allows you to grasp some logic points to check.
See the comments in the code below.
public boolean isNumeric(String input) {
// First trim input of trailing spaces
input = input.trim();
// test on 0 length
if(input.length == 0) {
return false;
}
// Loop through all characters to test
// if they are valid
for(char c : input.toCharArray()) {
if (!Character.isDigit(c)) return false;
}
return true;
}
You can then call it like this.
if(this.isNumeric(raad)) {
// your code here
}
Further more, learn about the single responsiblity principle.
There are some serious flaws in your code. I'd suggest you post it also on code review to get some useful pointers where to learn.

Related

How to fix the logic in my do-while loop, and then applying the try-catch block to catch and display an error message from another class?

The homework instructs to create a loop requesting for an String input. If the String has less than 20 characters, it displays what was just inputted. If if has more than 20 characters, the catch block will display a message stating that the String has too many characters. The only way to end the program is to input DONE. Otherwise, it continues to ask the user for Strings.
The catch block will display a message from another class.
I've attempted to do both do-while and while loops.
do
{
System.out.println("Enter strings, enter DONE when finished:");
userInputLength = input.nextLine();
try {
while(userInputLength.length() > 20)
{
System.out.println("Please try again:");
userInputLength = input.nextLine();
}
}
catch(StringTooLongException e) //Error here
{
//Not sure how to call the super() in StringTooLongException class.
}
while(userInputLength.length() <= 20)
{
String message = userInputLength;
System.out.println("You entered: " + message);
userInputLength = input.nextLine();
}
}
while(userInputLength.toString() == "DONE");
}
}
public StringTooLongException()
{
super("String has too many characters!");
}
Before I started getting the error on my catch block after adding both try-catch blocks, I was able to output long strings, then short strings. But if I attempt to write long strings after the short strings, the program ends.
it's gonna work. Look at my code and compare with yours.
First: don't compare strings with ==, always choose the equals method.
You do not need 3 whiles block, you need only one while and 2 IF'S one for string > 20 and another for string < 20 (look, if the string contains exactly lenght of 20, the program will output nothing)
And you need to create your own exception, it is very easy.
import java.util.Scanner;
public class ReadString {
public static void main(String[] args) {
String userInputLength;
Scanner input = new Scanner(System.in);
/*
* . If the String has less than 20 characters, it displays what was just
* inputted. If if has more than 20 characters, the catch block will display a
* message stating that the String has many characters. The only way to end the
* program is to input DONE. Otherwise, it continues to ask the user for
* Strings.
*/
do {
System.out.println("Enter strings, enter DONE when finished:");
userInputLength = input.nextLine();
try {
if (userInputLength.length() > 20) {
throw new StringTooLongException("String is too long");
} else {
System.out.println(userInputLength);
}
} catch (StringTooLongException e) // Error here
{
System.out.println(e.getMessage());
}
} while (!userInputLength.toString().equals("DONE"));
}
Exception class
public class StringTooLongException extends RuntimeException{
public StringTooLongException(String message) {
super(message);
}
}
Try to understand it :D !!!

Guessing Game Help :)

Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!

Printing out an Expression manipulated by a Stack JAVA

Hey guys so heres my question. I've got a class that manipulates a stack of Fractions and it is an RPN Evaluator. I'm newer to Java and only know basic data structures. This is a project for a class but I'm kinda bummed. I need to print out the expression that I used OR print out the expression until the RPN expression isn't valid denoted by valid = false/true I have a specific way I have to print it out and ill give an example but I cannot figure out how to do it... I have a queue available to me to use but I must use both a stack and a queue. I realize the code is yuck but its because I haven't begun my cleanup of that class yet. Here is an example of the output I need if the inputs are as follows.... Note that the input is in quotes minus the quotes
Input************************************Output
"(2/5)(1/2) * * #" *********** Expression 3 is: (2/5)(1/2)**
"(3/1)T ^ (3/2) #" *********** Expression 4 is: (3/1)T
Here is my class(I know it's sloppy...and the rules are very restrictive on what I can and can't use. No linked lists etc....)
import java.util.Scanner;
public class RpnEvaluator
{
private final int MAX_TOKEN = 20;
private Scanner stdin;
private int count = 0;
public void run() throws java.io.IOException
{
runOnce();
}
public boolean isOperator(String input)
{
String[] oprtr = {"+", "-", "*"};
for(String choice: oprtr)
if(choice.equals(input))
return true;
return false;
}
public boolean isOperation(String input)
{
if(input.startsWith("(", 0))
return true;
return false;
}
public Fraction runOperation(String choice, Fraction op2, Fraction op1)
{
Fraction newFract = new Fraction();
if(choice.equals("*"))
newFract = new Fraction(op1.times(op2));
else if(choice.equals("+"))
newFract = new Fraction(op1.plus(op2));
else if(choice.equals("-"))
newFract = new Fraction(op1.minus(op2));
return newFract;
}
public void runOnce()
{
String readIn = "";
boolean valid = true;
Fraction op1 = null, op2 = null, answer = null, myFract;
Queue myQueue = new Queue(MAX_TOKEN);
Stack myStack= new Stack(MAX_TOKEN);
stdin = new Scanner(System.in);
while(stdin.hasNext() && valid == true)
{
readIn = stdin.next();
if(readIn.equals("#"))
{
break;
}
else if(!isOperator(readIn) && isOperation(readIn))
{
myFract = new Fraction(readIn);
myStack.push(myFract);
}
else if(isOperator(readIn))
{
if(myStack.isEmpty())
valid = false;
else
op2 = (Fraction)myStack.pop();
if(myStack.isEmpty())
valid = false;
else
op1 = (Fraction)myStack.pop();
myStack.push(runOperation(readIn, op2, op1));
}
else
valid = false;
}
if(myStack.isEmpty())
valid = false;
else
answer = (Fraction)myStack.pop();
if(!myStack.isEmpty())
valid = false;
if(valid == false)
{
System.out.print("Expression " + ++count + ": ");
System.out.println("Invalid Expression");
}
else
{
System.out.println("Expression " + ++count + ": ");
System.out.println("The value is: " + answer.toString());
}
clear(myStack, myQueue);
}
public void clear(Stack myStack, Queue myQueue)
{
myStack.clear();
myQueue.clear();
}
}
I've got a class that manipulates a stack of Fractions and it is an RPN Evaluator.
No it isn't. It's an attempt, but it doesn't handle parentheses at all, or operator precedence. You need to look up the Dijsktra shunting-yard algorithm. If this is an assignment I have no doubt that this algorithm was mentioned in class, probably at great length.
I realize the code is yuck but its because I haven't begun my cleanup of that class yet.
The best way to cleanup a class is not to fill it with dirt in the first place. Writing code that has to be subsequently removed is a double waste of time.
Ok it is very unclear what you are asking and your code doesn't make too much sense and the fraction variable fraction is unknown.
and just a note here always clean up your code as write it since later you will never know where it is and will always be confusing.
try http://www.planet-source-code.com/vb/scripts/search.asp?lngWId=2.
for some examples, they always have what i need.
and if you are new to java and want to know more i would suggest the book Java Programming: From Problem Analysis to Program Design, it explains everything from main method to GUI design.
and in future please explain your problem in more detail, we have no idea what you are asking.
Thanks.

check string for integers?

Ok, I posted once earlier but it was locked due to not demonstrating a basic understanding, and the answers I did get before it was locked didn't help me. I'm at a super beginner level of java and this is what I want my program to do (will post code at end). I want the user to input anything they want. Then, if it is not a number, I want it to display that they need to input a number. Then, after they input a number, I want it to display whether or not that number is even or odd. I read about parseInt and parseDouble but i can't figure out how to get it to work how I want. I am not sure any more if parsing is what i want to do. I dont want to instantly convert it to numbers, just to check if it IS a number. then i can proceed to do things after the program has determined if it is a character or number. thanks for any help and let me know if you need more information!
ok i changed some things and used a lot of code from no_answer_not_upvoted. here is what i have now. it runs fine and works with negative and positive whole numbers as specified in the directions. the only thing that bugs me is after all is said and done, i get this error in the compile box at the bottom of eclipse. the program does what is intended and stops appropriately but i dont understand why i am getting this error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at monty.firsttry2.main(firsttry2.java:21)
public static void main(String[] args) {
System.out.print("Enter a character or number. This program will run until you enter a whole number, then it will"
+ "tell you if it was even or odd.");
while (true) {
Scanner in=new Scanner(System.in);
int num;
while(true) {
String input=in.nextLine();
try {
num=Integer.parseInt(input);
break;
}
catch (NumberFormatException e) {System.out.print("That wasn't a whole number. Program continuing.");}
}
if (num==0) {System.out.print("Your number is zero, so not really even or odd?");}
else if (num%2!=0){System.out.print("Your number is odd.");}
else {System.out.print("Your number is even");}
in.close();
}
}
}
Assumption
A String is to be considered a number if it consists of a sequence of digits (0-9), and no other characters, except possibly an initial - sign. Whereas I understand that this allows Strings such as "-0" and "007", which we might not want to consider as numbers, I needed some assumptions to start with. This solution is here to demonstrate a technique.
Solution
import java.util.Scanner;
public class EvensAndOdds {
public static final String NUMBER_REGEXP = "-?\\d+";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(;;) { // Loop forever
System.out.println("Enter a number, some text, or type quit");
String response = input.nextLine();
if (response.equals("quit")) {
input.close();
return;
}
if (response.matches(NUMBER_REGEXP)) { // If response is a number
String lastDigit = response.substring(response.length() - 1);
if ("02468".contains(lastDigit)) {
System.out.println("That is an even number");
} else {
System.out.println("That is an odd number");
}
} else {
System.out.println("That is not a number");
}
}
}
}
Justification
This solution will match a number of ANY length, not just one that will fit into an int or a long; so it is superior to using Integer.parseInt or Long.parseLong, which both fail if the number is too long. This approach can also be adapted to more complicated rules about what constitutes a number; for example, if we decided to allow numbers with comma separators (such as "12,345" which currently will be treated as not a number); or if we decided to disallow numbers with leading zeroes (such as "0123", which currently will be treated as a number). This makes the approach more versatile than using Integer.parseInt or Long.parseLong, which both come with a fixed set of rules.
Regular expression explanation
A regular expression is a pattern that can be used to match part of, or all of a String. The regular expression used here is -?\d+ and this warrants some explanation. The symbol ? means "maybe". So -? means "maybe a hyphen". The symbol \d means "a digit". The symbol + means "any number of these (one or more)". So \d+ means "any number of digits". The expression -?\d+ therefore means "an optional hyphen, and then any number of digits afterwards". When we write it in a Java program, we need to double the \ character, because the Java compiler treats \ as an escape character.
There are lots of different symbols that can be used in a regular expression. Refer to http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for them all.
this shows you how to do it
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
try (Scanner in = new Scanner(System.in)) {
int n;
while (true) {
String input=in.nextLine();
try {
n = Integer.parseInt(input);
break;
} catch (NumberFormatException e) {
System.out.println("you did not enter just an integer, please try again");
}
}
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}
}
As is already mentioned in other answers, you will need to call parseDouble statically with
Double theNumber = Double.parseDouble(numberString);
Next you will want to look at wrapping this in a try/catch so that you can do the even/odd check if theNumber is created or set the error message if an exception is caught.
Since you are a beginner, you need to understand the difference between numbers (integers, double, strings, characters), so the following will guide you.
First, read input one line at a time,
Java read line from file)
Then scan line looking for characters that form what you consider to be an integer (allow leading spaces?, then '+' or '-', then digits 0-9, and then trailing spaces.
Here are the rules (for integers)
leading spaces ok (this is up to you) (how: How to check if a char is equal to an empty space?)
optional single '+' or '-'
one or more digits (how: How to check if a character in a string is a digit or letter)
optional trailing space(s) (again, this is up to you)
Anything other than this pattern violates the test for 'is this an integer'. Btw, Double is an extended precision real number.
import java.lang.*;
import java.util.Scanner;
public class read_int
{
public static boolean isa_digit(char ch) {
//left as exercise for OP
if( ch >= '0' && ch <= '9' ) return true;
return false;
}
public static boolean isa_space(char ch) {
//left as exercise for OP
if( ch == ' ' || ch == '\t' || ch == '\n' ) return true;
return false;
}
public static boolean isa_integer(String input) {
//spaces, then +/-, then digits, then spaces, then done
boolean result=false;
int index=0;
while( index<input.length() ) {
if( isa_space(input.charAt(index)) ) { index++; } //skip space
else break;
}
if( index<input.length() ) {
if( input.charAt(index) == '+' ) { index++; }
else if( input.charAt(index) == '-' ) { index++; }
}
if( index<input.length() ) {
if( isa_digit(input.charAt(index)) ) {
result=true;
index++;
while ( isa_digit(input.charAt(index)) ) { index++; }
}
}
//do you want to examine rest?
while( index<input.length() ) {
if( !isa_space(input.charAt(index)) ) { result=false; break; }
index++;
}
return result;
}
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
Scanner in=new Scanner(System.in);
String input=in.nextLine();
if( isa_integer(input) ) {
System.out.print("Isa number.");
}
else {
System.out.print("Not a number.");
}
}
}

Loop Keyword Program Homework

It will ask the user for a keyword to search for. Then, it will ask the user to enter sentences over and over. The user can stop the process by typing “stop” instead of a sentence (which means, of course, that we can’t analyze the one word sentence ‘stop’, but that is OK). Once the user has finished entering the sentences, the program should display the following statistics:
The total number of sentences entered
The total number of sentences that contain the keyword
The average starting position of the keyword in the sentences that contain the keyword.
Can somebody help me put this program together? For #3 we only do average position of the sentences that contain the keyword.
I have the loop part, and for #3 I'm guessing we would use indexOf. #2 inputString.contains(keyword) I'm guessing? Can somebody help me with 1-3 and putting them into a Java program? Thanks.
import java.util.Scanner;
public class Lab6Loops {
public static void main(String[] args) {
String keywordString;
String inputString;
Scanner keyboard = new Scanner (System.in);
int numofSentences = 0;
int numofKeyword = 0;
System.out.println ("Enter a keyword. We will search each sentence for this word.");
keywordString = keyboard.nextLine ();
System.out.println ("Please enter a sentence or type 'stop' to finish");
inputString = keyboard.nextLine ();
while( !inputString.equals ("stop"))
{
if(inputString.contains (inputString));
numofSentences = numofSentences + 1;
if(inputString.contains (keywordString));
numofKeyword = numofKeyword + 1;
System.out.println ("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}
}
I like having self-documenting code, so here are a couple suggestions for how you can have a nice tight main loop:
functional-ish semantics
public void loop() {
// TODO: ask for the keyword and store it somewhere
while(true) {
try {
updateStatistics(checkOutput(getSentence()));
} catch (EndOfInput) {
printStatistics();
}
}
}
Object-Oriented
public void loop() {
String keyword = myPrompter.getNextSentence();
myAnalyzer.setKeyword(keyword);
while (true) {
String sentence = myPrompter.getNextSentence();
AnalysisResult result = myAnalyzer.analyze(sentence);
if (result.isEndOfInput()) {
myAnalyzer.printStatistics();
return;
}
}
}
What both of these approaches gives you is a simple framework to plug in the specific logic. You could do all of it inside the main loop, but that can get confusing. Instead, it's preferable to have one function doing one task. One function runs the loop, another gets the input, another counts the # of sentences, etc.
Sometimes I'll start with those little functions, and build the app from the bottom-up, so I'd write a method that takes a string and returns true/false depending on if it's the string "stop". You can even write unit tests for that method, so that when you're building the rest of the app, you know that method does what you intended it to. It's nice to have lots of modular components that you can test along the way, rather than writing a huge long loop and wondering why it's not doing what you want.
sounds like you need to prompt the user for an initial input then enter in to a loop that will last until the user presses stop (or whatever), in each iteration you need to prompt the user for a sentence, if the user inputs data increment one counter that stores the number of sentences, test the sentence against the keyword entered and increment a second counter as applicable, you will also need to push the position that the word occured in to a stack to later get the average which should be the sum of the stack divided by the size. you should be able to use indexOf() to get the position.
package console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Console {
static float averagePositionInSentence = 0;
static String searchTerm = "";
static int noOfSentencesEntered = 0;
static int noOfMatches = 0;
public static void main(String[] args) {
searchTerm = writeToConsoleAndReturnInput("Add phrase to search for.");
writeToConsole("Now type some sentences. To exit type the word 'stop' on its own");
mainInputLoop();
outputResults();
}
public static void mainInputLoop() {
boolean ended = false;
while (!ended) {
try {
String input = readLineFromConsole();
if (!input.equalsIgnoreCase("stop")) {
maintainStatisticalData(input);
} else {
ended = true;
}
} catch (Exception e) {
writeToConsole("There was an error with your last input");
}
}
}
public static void outputResults() {
writeToConsole("You entered " + noOfSentencesEntered + " sentences of which " + noOfMatches + " conatined the search term '" + searchTerm + "'");
writeToConsole("");
writeToConsole("On average the search term was found at starting position " + (averagePositionInSentence / noOfSentencesEntered) + " in the sentence");
}
public static void maintainStatisticalData(String input) {
noOfSentencesEntered++;
if (input.contains(searchTerm)) {
noOfMatches++;
int position = input.indexOf(searchTerm)+1;
averagePositionInSentence += position;
}
}
//terminal helper methods
public static void writeToConsole(String message) {
System.out.println(message);
}
public static String writeToConsoleAndReturnInput(String message) {
System.out.println(message);
try {
return readLineFromConsole();
} catch (IOException e) {
//should do something here
return "Exception while reading line";
}
}
public static String readLineFromConsole() throws IOException {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
return in.readLine();
}
}

Categories