11 Replies - 464 Views - Last Post: 04 February 2012 - 10:54 PM Rate Topic: -----

Topic Sponsor:

#1 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 09:39 PM

Hello. I am writing a program that is supposed to calculate the average of three test scores. So far, all I have learned are things like creating simple classes, but most of what I learned so far in my class is in the code. The problem with my code is, if I were to just press 'Enter' on a JOptionPane.showInputDialog without entering any data, the program will crash when it tries to calculate it. Since i have not even learned conditionals yet, I'm just curious how do I go about preventing this? (My current code has conditionals since I read ahead, but I'm still crashing.)

I've tried setting the if statement to either check for: " ", "", "\n", and 'null' to no avail.

The error I get:

Quote

Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:992)
at java.lang.Double.parseDouble(Double.java:510)
at TestScores_1.averageScore(TestScores_1.java:73)
at TestScores_1_Input.main(TestScores_1_Input.java:16)

public class TestScores_1
{
	// Declares the three test scores as strings, later to be parsed as double's.
	
	private String testScore_1, testScore_2, testScore_3;
	
	// This is a constructor method, that 'initializes' a new TestScores_1 object, with the specified values.
	
	public TestScores_1()
	{
		testScore_1 = null;
		testScore_2 = null;
		testScore_3 = null;
	}
	
	// These are the mutator methods, where the user will set the 
	// values for testScore_1, testScore_2, and testScore_3.
	
	public void set_1(String test1)
	{
		if (test1 == null) {
			testScore_1 = "0";
		} else {
			testScore_1 = test1;
		}
		
	}
	
	public void set_2(String test2)
	{
		if (test2 == null) {
				testScore_2 = "0";
			} else {
				testScore_2 = test2;
			}
				
	}
	
	public void set_3(String test3)
	{
		
		if (test3 == null) {
				testScore_3 = "0";
			} else {
				testScore_3 = test3;
			}
				
	}
	
	// These are the accessor methods, that will retrieve the values of the tests.
	
	public String getTest_1()
	{
		return testScore_1;
	}
	
	public String getTest_2()
	{
		return testScore_2;
	}
	
	public String getTest_3()
	{
		return testScore_3;
	}
	
	// This method AVERAGES the test scores.
	
	public double averageScore()
	{
		double t1, t2, t3, average_Score;
		
		t1 = Double.parseDouble(testScore_1);
		t2 = Double.parseDouble(testScore_2);
		t3 = Double.parseDouble(testScore_3);
		
		average_Score = (t1 + t2 + t3) / 3;
		
		return average_Score;
	}
}
	
	


import javax.swing.JOptionPane;

class TestScores_1_Input {
	public static void main(String[] args) {
		
		TestScores_1 testInput = new TestScores_1();
		
		JOptionPane.showMessageDialog(null, "This program will take 3 user-inputted test scores and average them.");
	
		testInput.set_1(JOptionPane.showInputDialog("What is your first test score?"));
		testInput.set_2(JOptionPane.showInputDialog("What is your second test score?"));
		testInput.set_3(JOptionPane.showInputDialog("What is your third test score?"));
		
		JOptionPane.showMessageDialog(null, "Your three scores are: " + testInput.getTest_1() + ", " + testInput.getTest_2() + ", "            											+ testInput.getTest_3());
		
		if (testInput.averageScore() <= 25)
		{
			JOptionPane.showMessageDialog(null, "You're a dumb faggot. Your average is: Faggot");
		}
		else {
			JOptionPane.showMessageDialog(null, "Your average is: " + testInput.averageScore());
		}
	
		System.exit(0);
		
	}
}




Is This A Good Question/Topic? 0
  • +

Replies To: Checking a JOptionPane.showInputDialog for a 'null' value

#2 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 09:44 PM

Please excuse my language in my code. It was a joke I was playing on a friend, but I forgot to take it out.
Was This Post Helpful? 0
  • +
  • -

#3 Mylo  Icon User is offline

  • D.I.C Regular

Reputation: 135
  • View blog
  • Posts: 493
  • Joined: 11-October 11

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:06 PM

Since when did jokes become about saying abusive language, it seems to be the normal thing now days =/

Anyway, as to your question, you can place the JOption pane in a loop.


String result = "";
while ("".equals(result) || " ".equals(result) || ...)
{
   result = optionpane...;
}



that will basically do what your asking. However, lets say someone enters " " with multiple spaces, or through out numbers. You could use a regex to remove spaces (cant help you with that) or create another method that will remove all spaces and invalid characters from the entered string.

public String stripInvalidCharacters(String c)
{
   // " 1  4 3 3" could return "1433";
}


This post has been edited by Mylo: 04 February 2012 - 10:06 PM

Was This Post Helpful? 0
  • +
  • -

#4 smohd  Icon User is offline

  • Critical Section
  • member icon



Reputation: 1644
  • View blog
  • Posts: 4,126
  • Joined: 14-March 10

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:10 PM

Quote

I've tried setting the if statement to either check for: " ", "", "\n", and 'null' to no avail.

 if (test1 == null) {

But "", " " and "\n" are not null!!! So probably will be accepted.

Quote

lets say someone enters " " with multiple spaces, or through out numbers. You could use a regex to remove spaces

Simply trim() the input and check if it is equal to "" for exceeding spaces. About if it is between numbers he can use replace() methods to remove them also

This post has been edited by smohd: 04 February 2012 - 10:12 PM

Was This Post Helpful? 1
  • +
  • -

#5 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:12 PM

View PostMylo, on 04 February 2012 - 10:06 PM, said:

Since when did jokes become about saying abusive language, it seems to be the normal thing now days =/Anyway, as to your question, you can place the JOption pane in a loop.
String result = "";while ("".equals(result) || " ".equals(result) || ...){   result = optionpane...;}
that will basically do what your asking. However, lets say someone enters " " with multiple spaces, or through out numbers. You could use a regex to remove spaces (cant help you with that) or create another method that will remove all spaces and invalid characters from the entered string.
public String stripInvalidCharacters(String c){   // " 1  4 3 3" could return "1433";}


Thanks for the help, but I don't know what you mean. I'm in an Intro class, and still fairly new. So maybe after I read my next Chapter, I'll look more at what you said. Thanks for all your help though! And I know, I know. The abusive language was bad. It was an inside joke thing, but sorry again.

View Postsmohd, on 04 February 2012 - 10:07 PM, said:

Quote

I've tried setting the if statement to either check for: " ", "", "\n", and 'null' to no avail.
 if (test1 == null) {
But "", " " and "\n" are not null!!! So probably will be accepted.


I have tried
test1 == ""
test1 == " "
test1 == "\n"
test1 == null

None of them work.
Was This Post Helpful? 0
  • +
  • -

#6 smohd  Icon User is offline

  • Critical Section
  • member icon



Reputation: 1644
  • View blog
  • Posts: 4,126
  • Joined: 14-March 10

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:21 PM

Dont wory about all of them, since you use showInputDialog() which returns string, take the input, trim() it to remove spaces( and if you want to replace in between spaces), then compare it with "". Something like:
public void set_1(String test1){
   test1 = test1.trim();
   if(test1.equals("")){
     testScore_1 = "0";

But this will not prevent user prom inputting other non numeric characters like letters or space in between
Was This Post Helpful? 1
  • +
  • -

#7 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:27 PM

View Postsmohd, on 04 February 2012 - 10:21 PM, said:

Dont wory about all of them, since you use showInputDialog() which returns string, take the input, trim() it to remove spaces( and if you want to replace in between spaces), then compare it with "". Something like:
public void set_1(String test1){
   test1 = test1.trim();
   if(test1.equals("")){
     testScore_1 = "0";

But this will not prevent user prom inputting other non numeric characters like letters or space in between


Thanks! That works! But my professor won't allow code we have not yet learned. Which means, along with the code you've seen, which is the first 3 chapters of my book, Chapter 4, is the only other chapter he would allow code from, and it uses logic operators. I don't learn trim() until halfway through the course. What does the input dialog return? And is this the only way I can do it?
Was This Post Helpful? 0
  • +
  • -

#8 Mylo  Icon User is offline

  • D.I.C Regular

Reputation: 135
  • View blog
  • Posts: 493
  • Joined: 11-October 11

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:35 PM

Yes, smohd that would be easier, replace(), forgot about that.

As for what I said, it's a basic solution, but it will not work well for all types of input without listing them all.

The while loop will keep asking for the users input while he enters " " || (or) "" || .. and so on.

There is always several ways to go about a problem. But to make what the user entered valid (the user won't always kindly enter spaces or valid input), you can try something like this:

	public static void main(String[] args)
	{
		String result = "";
		result = JOptionPane.showInputDialog("What is your third test score?");
		System.out.println(makeValid(result));
	}

	public static String makeValid(String s)
	{
                // what characters can the user enter
		String validChars = "0123456789";
                // what to return later
		String newString = "";
                // for each valid character, add it to the new string
		for (char c : s.toCharArray())
		{
			if (validChars.contains(Character.toString(c)))
			{
				newString += c;
			}
		}
                // return the new string
		return newString;
	}



Depending on your needs, you may want to adjust the above to return true or false, saying if it is valid or not, then do this:

	public static void main(String[] args)
	{
		String result = "";
		do
			result = JOptionPane.showInputDialog("What is your third test score?");
		while (!isInputValid(result));
	}



But maybe if you don't understand what it happening, just go with the spaces thing. You should be able to apply what you learn later on to do some simple error checking and so on.

Also, another common error is using == instead of .equals() on objects (Which includes Strings). This is important since you are replacing your objects with new objects return of the .trim() method. so you .equals() instead of ==.

if (string.equals("")...)

This post has been edited by Mylo: 04 February 2012 - 10:40 PM

Was This Post Helpful? 0
  • +
  • -

#9 smohd  Icon User is offline

  • Critical Section
  • member icon



Reputation: 1644
  • View blog
  • Posts: 4,126
  • Joined: 14-March 10

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:37 PM

Quote

I don't learn trim() until halfway through the course

And that is the string class method. Then why you use String class at all!

Quote

What does the input dialog return? And is this the only way I can do it?

I have said that, the one you use and most of other overloads return String, other returns Object.
There are a lot of ways doing things, and a lot of advice has been given above. So your choice!
Was This Post Helpful? 0
  • +
  • -

#10 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:41 PM

View Postsmohd, on 04 February 2012 - 10:37 PM, said:

Quote

I don't learn trim() until halfway through the course

And that is the string class method. Then why you use String class at all!

Quote

What does the input dialog return? And is this the only way I can do it?

I have said that, the one you use and most of other overloads return String, other returns Object.
There are a lot of ways doing things, and a lot of advice has been given above. So your choice!


I know it is of the String class, but we haven't even learned much of it. All we've learned are like, toUpperCase(), charAt(), simple stuff. Trim seems simple enough, but my professor won't give credit if any of the code isn't taught yet, and a majority of what has been written here, although extremely informative, won't give me a grade. Thanks for all your help though, because from the looks of it, my professor doesn't need error checking. I'll have to ask.
Was This Post Helpful? 0
  • +
  • -

#11 Mylo  Icon User is offline

  • D.I.C Regular

Reputation: 135
  • View blog
  • Posts: 493
  • Joined: 11-October 11

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:51 PM

Well, it is hard if you can't use those methods, if you have learnt for loops, you can use the charAt() method to check for spaces, and append non spaces to a new string. But that's about all I can think of. Otherwise, if the course is just being simple and not expecting of things like error checking (maybe not the right word) then you could just leave it as is and assume the user will only enter numbers.
Was This Post Helpful? 0
  • +
  • -

#12 newbcake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 04-February 12

Re: Checking a JOptionPane.showInputDialog for a 'null' value

Posted 04 February 2012 - 10:54 PM

View PostMylo, on 04 February 2012 - 10:51 PM, said:

Well, it is hard if you can't use those methods, if you have learnt for loops, you can use the charAt() method to check for spaces, and append non spaces to a new string. But that's about all I can think of. Otherwise, if the course is just being simple and not expecting of things like error checking (maybe not the right word) then you could just leave it as is and assume the user will only enter numbers.


I think our first assignment won't require error checking. I wish it did since it bothers my OCD.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1