LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-30-2011, 12:02 AM   #1
phoenixfire
Member
 
Registered: Nov 2006
Location: Australia
Distribution: Gentoo
Posts: 86

Rep: Reputation: 15
Java noob: How do i ask a true or false question?


I need to write a program that will ask the user a true of false question eg. "Is today a weekend?"

For what i've looked up i think it has something to do with a Boolean but i'm not really understanding how it works.

And help at all would be greatly appreciated.
 
Old 07-30-2011, 12:08 AM   #2
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
What don't you understand? Yes, Java has a data type called boolean that can store either true or false. You can simply ask the user the question and set your boolean variable to true or false depending on their answer.

Tell us specifically what you don't understand and post any attempt you've made at writing the code.
 
Old 07-30-2011, 12:24 AM   #3
phoenixfire
Member
 
Registered: Nov 2006
Location: Australia
Distribution: Gentoo
Posts: 86

Original Poster
Rep: Reputation: 15
The first thing i don't understand is how to enter the question. I am assuming it's something like:

Quote:
h1 = keyboard.nextInt(boolvar);
boolean boolvar;
if (h1 == true) {System.out.println ("It is a weekned");}
else if (h1 == false) {System.out.println ("It is not a weekend");}
Am i close?
 
Old 07-30-2011, 12:43 AM   #4
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
So the problem is you don't know how to read input? That's what you mean, right?

I'm not sure what class your keyboard object is, but the simple way to get keyboard input is like this.

The rest after getting the input is OK. Remember, though, the braces on the if and else are optional when you have only one statement.

Out of interest, does your class/book not show you how to do basic things like reading input?
 
Old 07-30-2011, 12:51 AM   #5
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
For future reference, you might want to look at the Java Tutorials, specifically "Trails Covering the Basics".
 
Old 07-30-2011, 01:52 AM   #6
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Hi, phoenixfire -

Perhaps this example might help:
Code:
import java.io.*;

class Tmp
{
  public static void main (String[] args) throws IOException
  {
    // Prompt user to enter something
    System.out.print ("Please enter a weekday (EX: \"monday\"): ");

    // Read their input
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = br.readLine ();

    // See if it's a valid weekday
    if (input.compareTo ("monday") == 0)
      System.out.println ("You entered Monday.");
    else if (input.compareTo ("tuesday") == 0)
      System.out.println ("You entered Tuesday.");
    // ... etc etc
    else if (input.compareTo ("sunday") == 0)
      System.out.println ("You entered Sunday.");
    else
      System.out.println ("Sorry: I don't recognize the day \"" + input + "\"");
  }
}
Sample output:
Quote:
C:\temp>javac Tmp.java

C:\temp>java Tmp
Please enter a weekday (EX: "monday"): tuesday
You entered Tuesday.

C:\temp>java Tmp
Please enter a weekday (EX: "monday"): Moose
Sorry: I don't recognize the day "Moose"
 
Old 07-31-2011, 05:20 AM   #7
Proud
Senior Member
 
Registered: Dec 2002
Location: England
Distribution: Used to use Mandrake/Mandriva
Posts: 2,794

Rep: Reputation: 116Reputation: 116
Quote:
if (input.compareTo ("monday") == 0)
Why not
if( string1.equals( string2 ) )
?

Also, Java 7 can do Switch/Case statements on Strings now.

And for a GUI example, http://download.oracle.com/javase/tu...og.html#create
Code:
final JOptionPane optionPane = new JOptionPane(
    "The only way to close this dialog is by\n"
    + "pressing one of the following buttons.\n"
    + "Do you understand?",
    JOptionPane.QUESTION_MESSAGE,
    JOptionPane.YES_NO_OPTION);
http://download.oracle.com/javase/tu...nPaneMetal.png
Or
Code:
int n = JOptionPane.showConfirmDialog(
    frame,
    "Would you like green eggs and ham?",
    "An Inane Question",
    JOptionPane.YES_NO_OPTION);
http://download.oracle.com/javase/tu...nTextMetal.png

Last edited by Proud; 07-31-2011 at 05:24 AM.
 
Old 07-31-2011, 10:38 PM   #8
phoenixfire
Member
 
Registered: Nov 2006
Location: Australia
Distribution: Gentoo
Posts: 86

Original Poster
Rep: Reputation: 15
Nylex thanks you very much for your useful link you've been a great help so far in both this and my other thread.

Thank you Paulsm4 for your well commented example, very helpful.

And thank you to Proud for providing a nice alternative.

I'll go over everything you've all given me and try to understand it completely and i'll let you know if my program works. Thanks again!

Edit: Nylex, the book we're using is called "Java: An Introduction to Problem Solving and Programming (6th Edition)" but unfortunately i haven't received it yet from amazon.com. Screwed if i'm paying the price they're asking for it at the Uni bookshop.

Last edited by phoenixfire; 07-31-2011 at 10:41 PM. Reason: Missed some info
 
Old 07-31-2011, 11:41 PM   #9
phoenixfire
Member
 
Registered: Nov 2006
Location: Australia
Distribution: Gentoo
Posts: 86

Original Poster
Rep: Reputation: 15
Alright, now i'm getting
Quote:
Error: The operator && is undefined for the argument type(s) int, boolean
When trying to compile. As i think i'm getting really close i'll just post the entire question and my program.

Quote:
////////////////////////////// PROBLEM STATEMENT //////////////////////////////
// Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a //
// boolean indicating if we are on vacation, print a string of the form //
// "7:00" indicating when the alarm clock should ring. Weekdays, the alarm //
// should be "7:00" and on the weekend it should be "10:00". Unless we are //
// on vacation -- then on weekdays it should be "10:00" and weekends it //
// should be "off". //
// 1, false -> "7:00" //
// 1, false -> "7:00" //
// 1, false -> "7:00" //
///////////////////////////////////////////////////////////////////////////////

// >>>>>> Your Java Code Fragment starts here <<<<<<
Scanner keyboard = new Scanner (System.in);
int d1;
System.out.println("What day is it today? (0=sun, 1=mon, 5=fri, 6=sat, ect");
d1 = keyboard.nextInt( );
System.out.println("Is it a holiday today?");
Boolean h1 = keyboard.nextBoolean();
if (d1 >= 1 && d1<=5 && h1 == true) {System.out.println ("10:00");}
else if (d1 >= 1 && d1<=5 && h1==false) {System.out.println ("7:00");}
else if (d1 == 0||6 && h1==true) {System.out.println ("off");}
else if (d1 == 0||6 && h1==false) {System.out.println ("10:00");}

// >>>>>> Your Java Code Fragment ends here <<<<<<
So how can && be undefined? Does it not mean AND?
 
Old 08-01-2011, 12:07 AM   #10
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Hi -

Suggestion:

1. Read input:
a) int day // Day
b) boolean isHoliday // Holiday

2. Write a "method" (for example, "alarmTime()") to compute the alarm time:
EXAMPLE:
Code:
class MyClass
{
  ...
  string alarmTime (int day, boolean isHoliday)
  {
    if (isHoliday)
    {
      if ( (day == 0) || (day == 6) )
        return "off"
      else
        return "10:00";
    }
    else
    {
      if ( (day == 0) || (day == 6) )
        return "10:00";
      else
        return "7:00";
    ...

Last edited by paulsm4; 08-01-2011 at 11:06 AM.
 
Old 08-01-2011, 12:22 AM   #11
phoenixfire
Member
 
Registered: Nov 2006
Location: Australia
Distribution: Gentoo
Posts: 86

Original Poster
Rep: Reputation: 15
Thanks for your reply but i have it working another way now.
Now i'm getting some kind of error.

For testing if we've completed the question or not they have given us a program that enters values into the program we've written and checks them against what the answer should be.

For the end result i've got
Quote:
Scanner keyboard = new Scanner (System.in);
int d1;
boolean h1;
//System.out.println("What day is it today? (0=sun, 1=mon, 5=fri, 6=sat, ect");
d1 = keyboard.nextInt( );
//System.out.println("Is it a holiday today?");
h1 = keyboard.nextBoolean();
if (d1 >= 1 && d1<=5 && h1 == true) {System.out.println ("10:00");}
else if (d1 >= 1 && d1<=5 && h1==false) {System.out.println ("7:00");}
else if (d1 <= 0 && d1 >=6 && h1==true) {System.out.println ("off");}
else if (d1 <= 6 && d1 >=6 && h1==false) {System.out.println ("10:00");}
With the questions commented out so that the program will only read the "10:00" ect.
The strange thing is it will run fine if i don't have them commented out but won't pass since the output also includes my 'please enter' questions but when they are commented out i get
Quote:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
when i try to run it.

Why would this happen?
 
Old 08-01-2011, 07:37 AM   #12
devnull10
Member
 
Registered: Jan 2010
Location: Lancashire
Distribution: Slackware Stable
Posts: 572

Rep: Reputation: 120Reputation: 120
Sounds like the program is reading all the input from your program. One (very ugly) workaround might be to print the questions to stderr instead of stdout.
I'd imagine your error may well be buffer related (ie, not being flushed) but I wouldn't like to say for definite as I've only had a 2 second glance at your code.
 
Old 08-01-2011, 11:34 PM   #13
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Quote:
Q: Why would this happen?
That's what debuggers are for .

Familiarize yourself with JDB (or your IDE's debugger, if you're using an IDE) and single step through it.

I believe that commenting out your prompt is probably "coincidence"; I do *not* believe stdin and stdout are somehow getting co-mingled together.

Another alternative, of course, is to try "BufferedReader" I suggested, or the JSwing approach another poster suggested.

But your best bet is a debugger. You should definitely familiarize yourself with at least one debugger; better sooner than later.

IMHO .. PSM
 
Old 08-02-2011, 04:04 AM   #14
Proud
Senior Member
 
Registered: Dec 2002
Location: England
Distribution: Used to use Mandrake/Mandriva
Posts: 2,794

Rep: Reputation: 116Reputation: 116
What was originally
Code:
if (d1 == 0||6 && h1==false) {System.out.println ("10:00");}
now seems to be
Code:
if (d1 <= 6 && d1 >=6 && h1==false) {System.out.println ("10:00");}
Firstly I think you're now aware that d1 == 0||6 isn't the correct shorthand for d1 == 0 || d1 == 6, but it also isn't equivalent to the latter logically.
d1 <= 6 && d1 >=6 is equal to d1 == 6, which mean d1 == 0 isn't tested. I think you meant d1 <= 0 && d1 >=6

As to why you're program behaves differently when you're not interleaving the out.printlns with the keyboard.nextTypes, consider that you're using a Scanner class wrapping System.in. Check how it behaves around giving empty tokens, blocking(aka waiting without you writing specific code to make it) differently when calling next() vs hasNext() (maybe you should wait while( !hasNext() ) ?), and that it may determine the end of the input has been reached before you want it to.

Last edited by Proud; 08-02-2011 at 04:32 AM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] diff - how do i read it as true or false? Markus72 Linux - Software 3 03-27-2011 04:13 AM
if statement ignoring true/false and proceeding anyway. Goblin_C_Noob Programming 4 03-30-2008 09:56 AM
comparison is always true/false jubaitca Programming 20 11-05-2006 06:55 PM
true or false? alaios Programming 7 07-16-2005 10:54 AM
Return true or false if I have ping reply Menestrel Programming 4 11-29-2004 12:40 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:38 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration