11 Replies - 4983 Views - Last Post: 19 June 2012 - 06:32 AM Rate Topic: -----

#1 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

If statements and user inputs

Posted 18 May 2012 - 11:48 PM

Hi there, extremely glad I accidentally stumbled across this site, as I'm in dire need of assistance.

I've recently started introduction to programming for university and am starting with Java, and have just recently made the (what feels like a giant) leap from Alice to Java.

So far we've covered variables and if statements and the like, and I'm just fiddling around in Eclipse doing some programming as practice and have encountered an issue.

I am using a scanner to take a user input and attempting to build a program to do one of those number guessing games. i.e. I'm thinking of a number, what is it?

I've doing okay so far (though have a lot of work to go) but have encountered an error. No matter what I try I can't seem to get the if statement right. Here is what I have so far

import java.util.Scanner;
public class RandomWork {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("What number am I thinking of?");
		Scanner user_input = new Scanner(System.in);
		String first_input;
		first_input = user_input.next();
		System.out.print("You have chosen " + first_input);
		String user = first_input;
		if(first_input < [unfinished]){
		
			
		}
	}

}



if(first_input) is meant to read the input the user has entered and determine if it's lower or higher than randomly generated number (which I haven't done yet - I plan to just write up a number for it to use to test the workings of everything else, firstly)

The error returned is The operator < is undefined the argument type(s) String, int

And quite frankly I have no idea where to go from here. any kind of assistance would be greatly appreciated!

Thanks,
James.

Is This A Good Question/Topic? 0
  • +

Replies To: If statements and user inputs

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: If statements and user inputs

Posted 19 May 2012 - 03:13 AM

Hopefully, you'll be as grateful to discover the wealth of information that can be found in Sun's (now Oracle's) Java tutorials. If you were to Google "java comparing strings", the second result would point you to "The Java Tutorials" and the article here.

That article is specific to Strings - your immediate concern - but it will be a stepping stone to the more general topic of comparing objects in Java. Don't go down that path just yet, but keep it in mind as a topic to delve into more deeply some other time.
Was This Post Helpful? 2
  • +
  • -

#3 Hikaroshi  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 42
  • Joined: 26-April 09

Re: If statements and user inputs

Posted 19 May 2012 - 04:33 AM

Hm, maybe I've misread the post/don't understand something, correct me if that's the case...

You want to create a guessing game program where the computer randomly generates a number and the user has to guess it correctly, yeah?

If that's the case, wouldn't you also need a line of code that acts as a number randomizer?
I think so... Another thing to consider, but maybe it's not the goal of your assignment, from what # to what # does the user have to guess from? http://www.cs.genese...nce/random.html or even better because you know your options: http://docs.oracle.c...til/Random.html

Oh, and... let's think about your error (I reread)...
So you know <, >, == are used to compare similar statements for the most part...

I want to compare two numbers, I want to know if 1 is greater than 10
therefore ideally 1 is a number and 10 is a number.

I want to compare two numbers. I want to know if "one" is greater than 10
how would that work if "one" is a word and 10 is a number? That's what your program is thinking... It cannot compare a string (in my example "one") to a number (in my example 10) because they're two different things.

Have you considered not getting the user input as a string?

-------------------
In terms of the if statement, what do you want to do? I think it's something like this:
1. You want to consider the option where the user guesses the right number
  • What happens then?

2. Inside of the case of the wrong number wouldn't you want to consider the options:
  • when the user guesses a number too high
    • What happens then?

  • when the user guesses a number too low
    • What happens then?

This post has been edited by Hikaroshi: 19 May 2012 - 04:45 AM

Was This Post Helpful? 2
  • +
  • -

#4 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

Re: If statements and user inputs

Posted 20 May 2012 - 10:42 PM

View PostHikaroshi, on 19 May 2012 - 04:33 AM, said:

I want to compare two numbers. I want to know if "one" is greater than 10
how would that work if "one" is a word and 10 is a number? That's what your program is thinking... It cannot compare a string (in my example "one") to a number (in my example 10) because they're two different things.

Have you considered not getting the user input as a string?


I haven't considered it, well, not until now. I am unsure of other ways to get the input at this time unfortunately. What would be the best way to iron out this particular issue? I have replaced the String with Int; would this be the better way to store variables numbers if I wish to compare them to another value with an if? (I suppose it is, since my if actually works now, lol)

As you said towards the beginning of your post, yeah, I do need a random number generator, but I was under the impression I'd be able to cross that bridge when I came to it, as the core issue (at least for myself at this time) is getting my head around all of the other stuff.

This is where I am at now

import java.util.Scanner;
public class RandomWorks{

	public static void main(String[] args){
		System.out.println("What number am I thinking of?");
		Scanner user_input = new Scanner(System.in);
		int first_input;
		first_input = user_input.nextInt();
		System.out.println("You have chosen " + first_input);
		if(first_input<10){
		System.out.println("I'm afraid that answer is incorrect, try again!");}
		else{
		System.out.println("I don't have a function for that just yet");}
}
}




The if/else is only there as a test to see if I had everything working fine. I guess I've come to the bridge of needing the random number generator now and comparing the user input to the generated number. The link that GregBrannon put up too is also immensely helpful.

If there is anything in there that needs pointing out to a newbie, or anything that could be done better/easier feel free to point it out. :D
Was This Post Helpful? 0
  • +
  • -

#5 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

Re: If statements and user inputs

Posted 20 May 2012 - 11:51 PM

Couldn't find where to edit my post, so to follow on:

I know I'm going to need some kind of loop, to repeat "Your answer is incorrect, please try again," and asking the user to input another answer. What would the best thing be for that situation? I was thinking a while loop, but don't they have to have a statement answer that is less/greater than or equal to? or are they able to be configured so that they will loop until the user input = n (where n is the random number generated by the program), and within that loop wouldn't I need a standard if statement to determine if the loop/program needs to be terminated for say, a correct guess?

Secondly is there a way for the program to tell the user to attempt to input a number that is higher or lower than their original guess? Ideally it would check if x </> than n (x is user input n is random number).. like.. trying to explain how i see this in my head haha. if(x < || > n){ .. and so on...

Is this doable in the way I am imagining, or do I need to go back to the drawing board? Am I at least on the right track?

Thanks,
James.
Was This Post Helpful? 0
  • +
  • -

#6 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: If statements and user inputs

Posted 21 May 2012 - 12:24 AM

If you're uncertain how many loops will be necessary, the while or do/while loops are excellent tools to do as you describe. Some use a while( true ) loop and break; out of it when the user signals or looping is no longer required for whatever reason. Another option is to use a value to indicate looping can stop,

int value = 1;
while ( value != 0 )
{
   // tell the user to input 0 to stop
   // and store the input in variable value
}

The above is known as using a sentinel to indicate the user's desire to stop.

You're at the discovery stage where you should code these ideas to see how they do or don't work. Trying everything you've suggested in short programs should take just a few minutes to code up, and you'll understand a lot better by doing. Add a feature, test and fix until you're satisfied, and add another feature, repeat.

As for checking the user's input and providing feedback, that would be done with an if statement. That's another feature.

This post has been edited by GregBrannon: 21 May 2012 - 12:27 AM

Was This Post Helpful? 1
  • +
  • -

#7 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

Re: If statements and user inputs

Posted 21 May 2012 - 02:20 AM

So I've progressed a little bit further, and have come to another minor hurdle.. I'm using a while loop to perform the task needed (determine if first_input is not equal to rndNumber) which certainly works, but of course it loops infinitely... break; will terminate the loop, but then if the incorrect input is entered in, then the program won't ask for a new input. The do...while certainly seemed to be ideal for this purpose but either I can't seem to implement in the way I'm intending, or it's not as ideal as I thought it would be.

On the other hand, maybe I'm doing it wrong entirely :D

Here's where I am up to:


import java.util.Scanner;
import java.util.Random;
public class RandomWorks{


	public static void main(String[] args){
		System.out.println("I am thinking of a number between 1 and 20 - What is it?");
		// The random number code is currently here to output the result of the random number above all else for testing purposes
		Random rndNumbers = new Random();
			int rndNumber = 1;
			rndNumber = rndNumbers.nextInt(20);
			System.out.println("The number is " + rndNumber);
			
		// The following code is to store the number a user inputs
		Scanner user_input = new Scanner(System.in);
			int first_input;
			first_input = user_input.nextInt();
			
		// The following code is to generate a random number between 1 and 20

			
		// The following code is a loop to determine if the value of first_input is not equal to rndNumber
		do{
			System.out.println("I'm sorry, that answer is incorrect. Please try again.");
		} while(first_input != rndNumber);
		}
	}


Was This Post Helpful? 0
  • +
  • -

#8 Hikaroshi  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 42
  • Joined: 26-April 09

Re: If statements and user inputs

Posted 21 May 2012 - 04:05 AM

You were right in the previous post (the one before this one recently posted) in terms of thinking about how to inform the user whether they're too high or too low in value.

Let's step back for a little bit.

We mentioned before that:
The user enters a number,
If the number is too low, what do you want to do?
You want to ask again, right?
If the number is too high, what do you want to do?
You want to ask again...

Until the user gets the number right, you want to stop...

Now let's fix that:

On the condition that the user doesn't get the answer correct.
  • There are two options for the user to guess:
    • The number is too high

    • The user's guess is too high, what do we want to do? We want them to try again.

  • The number is too low
    • The number is too low, what do we want to do? We want them to try again.

The user gets the answer correct, now stop.

You already have the pieces, you're just missing one little element which I've stated at the end of those two sentences above. You want them to try again.

You have the while loop which is the condition where the user doesn't get the answer correct and it'll terminate once they do. You had the if statement considering the condition whether the number inputted is too high or too low, that's good...

What you've failed to consider is how to make them try again. The only way to make them try again is to allow them another chance to input a guess while the condition of them not getting the correct answer is true on the grounds that what they've inputted is not the correct number (either too high or too low). I made it bold as a way to hint something to you.

This post has been edited by Hikaroshi: 21 May 2012 - 04:07 AM

Was This Post Helpful? 3
  • +
  • -

#9 Hikaroshi  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 42
  • Joined: 26-April 09

Re: If statements and user inputs

Posted 21 May 2012 - 04:24 AM

I also caught a little booboo of yours...

So... we're guessing a number from 1 to 20, right?

Why are you starting at 0? Haha...

I'll fix that line for you, because it's nothing (I think) you should scratch your head over when it'll all make sense to show you, and you're going to see it and it will also make sense to you.

rndNumber = rndNumbers.nextInt(20);

Gets transformed to
rndNumber = 1+rndNumbers.nextInt(20);

Was This Post Helpful? 1
  • +
  • -

#10 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

Re: If statements and user inputs

Posted 21 May 2012 - 05:17 PM

View PostHikaroshi, on 21 May 2012 - 04:05 AM, said:

What you've failed to consider is how to make them try again. The only way to make them try again is to allow them another chance to input a guess while the condition of them not getting the correct answer is true on the grounds that what they've inputted is not the correct number (either too high or too low). I made it bold as a way to hint something to you.


I've had a think about what you've said and have amended my code a little bit. Instead of using a do...while (which wasn't producing the desired results anyway) I have changed it to an if/else, which makes more sense in my head but then I am only a beginner.

		// The following code is a loop to determine if the value of first_input is not equal to rndNumber
			if(first_input == rndNumber)
			System.out.print("That is correct!");
			else{System.out.println("That is not correct, please try again.");
			}


The only thing I can think of is to build a new scanner within the if/else, as every time I've tried with some kind of other statement like loops to get the user to input again, it either won't allow input or immediately terminates.

But then I would need to build like a billion scanners wouldn't I? :(

Also thanks for pointing out

rndNumber = rndNumbers.nextInt(20);



I had no idea lol. I hadn't encountered a 0 yet :P
Was This Post Helpful? 0
  • +
  • -

#11 Hikaroshi  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 42
  • Joined: 26-April 09

Re: If statements and user inputs

Posted 21 May 2012 - 05:39 PM

No, the while/ do while loop was correct... I said that you had all the pieces but were missing an element.

Think about it again... While the condition of them not finding the answer has not been met you want to continue to ask them for a number, right?

So let's work in a general sense if that's the case.

While the answer is not correct:
-Ask again
Terminates upon having the correct answer.

Now, after that add in the if statements. Bear in mind I said in the previous post "...another chance to input a guess while the condition of them not getting the correct answer is true"

-----------
So, first remove the if statements but keep the while loop just as a test to see what we're aiming at. You knew that you needed it because you need to keep asking the user until they get it correct.

Once you do that part, all you need to do is consider those two conditions inside of the while loop. Or in the case of the do-while loop, you'd put it in the 'do' part, correct?

Just to tell you how the program works at a while loop, first it checks whether the condition has been met to have the need to go into the while loop (which means it looks at the part where you write while (...) {)
So once it finds out that it needs to go into the while loop, it does, so it goes on to the next line.

Then in the case of the if statements, it will look at the fist if statement, check to see if whatever you're checking it against has met the criteria to need to go onto the next line of that if statement. Let's say it does (well it has to in one of the two cases). When it goes on to the next line it performs a task, in this case it would be the task of informing the user that their number is too high, or too low.
Once it informs them it goes out of the if statement, then if there are any other lines that are inside of the while loop, it will visit those.

http://people.csail.....html#mode=edit
I want you to put this code into the text box and delete the sample code they've given, I wrote it for you to see it physically. It's python.

count = 0
while (count < 9):
    if (count <= 4):
       print "You're almost halfway there!", count
    elif (count >= 5):
        print "You're more than halfway there!", count
    count = count + 1
print "Good bye! You've arrived."



Count is incremented outside of the if statements, but is still in the while loop, I could have also written it that count would be incremented inside of both of the if statements, which would mean that I'd have two count = count + 1
Was This Post Helpful? 1
  • +
  • -

#12 xghostchantx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 18-May 12

Re: If statements and user inputs

Posted 19 June 2012 - 06:32 AM

I apologise for the massive delay in reply, and thankyou for all the help you've provided to me thus far.

I've recently been diagnosed with a very serious illness which has taken me away from work and study for quite some time.

I recently jumped back on to what I was doing (in addition to catching up on assignments) and thought I'd let you know where I'm at.

I had a think about what you'd posted about the if/do/while stuff and I proceeded to change it up a little, and now have it (almost) there!

		// The following code is a loop to determine if the value of first_input is not equal to rndNumber and react accordingly
			if(first_input == rndNumbers){
				System.out.println("Well done, that was a correct guess");
				}
				else{
					do{
						System.out.println("I'm sorry, that's incorrect. Please try again.");
						int second_input = user_input.nextInt();
					}while(first_input != rndNumbers);
				}



It will terminate if the first guess is correct (first if condition met), and loop correctly if the number isn't guessed correctly on subsequent attempts - however if the correct number is entered, it won't terminate on the correct condition (input = rndNumber).

Looking it over now, I would surmise that it's because the while is still attempting to read first_input, however if I modify to second_input Eclipse tells me the variable doesn't exist, so I'm a little bit confused.

But, progress is progress. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1