Using Scanner to change boolean in java - java

This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}

For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}

Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.

You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.

package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards

Related

Something can't be resolved?

Trying to test my java "skills" and make a text based game--except i can't get the user input. i already importd the scanner class, and it works well w/ integers so idk what the problem is quite frankly. whenever i try to compile it, the lines containing "String name = scanner.next();" show up with a 'Scanner cannot be resolved' error.
import java.util.Scanner;
public class CH1 {
public static void main (String args[]) {
Scanner s= new Scanner( System.in);
int answer;
System.out.println ("You're in grave danger, but first, I must know your name. Will you tell me? ");
answer = s.nextInt();
if (answer == 1) {
System.out.println ("I respect your decision, but I'll need to know your name
if you turn up dead, unless you want to have a one man funeral.");
System.out.println ("What's your name?");
String name = scanner.next();
}
else if (answer == 2) {
System.out.println("Great, now what's your name?");
String name = scanner.next();
}
else {
System.out.println(" Huh? I didn't really get that. (1 for no, 2 for yes.)");
}
}
}
You named that scanner s first!
You can't just use a different name later on!
So simply change the scanner variable name to "scanner" and keep using that name.
Beyond that: Single character variable names are something you almost never do (except for index values in for loops). The point is: variable names should say something about the thing they denote. "s" says nothing!

How do I use switch statements inside if else statements

I'm trying to write a program that can decide what mechanism a organic reaction will go through using a series of if else and switch statements.
Could you guys help me figure out what I'm doing wrong here? I'm having a problem getting the first if else statement to work. The program runs on my computer(I'm using the BlueJ editor), but when I respond to the first question "Is it soluble in solution?" it defaults to the else statement. The switch statements on the inside of the if else statement works fine by itself.
Can I use switch statements inside if else statements? Is there an easier way to program this?
Could you also explain why it doesn't work, or why another method would be more efficient?
Thanks a ton :)
import java.util.Scanner;
/**
* This program will decide what mechanism a reaction will undergo given information about the reactants.
* I will also include a mechanism to give a rudimentary explanation of the decision making process to
* get the reaction mechanism.
*/
public class mechanism
{
public static void main(String[] args)
{
System.out.println("Hello, this program is designed to figure out what mechanism a reaction will under go.");
//The decision tree will be a series of if-else statements. If I find a better method, I will use that
System.out.println("Is the reactant soluble in the solvent? Answer in yes or no.");
Scanner keyboard = new Scanner(System.in);
String Solubility = keyboard.next(); //Defines if the reactant is soluble in the solvent
String functional = "unassigned";//Defines if the functional roup is primary secondary or tertiary
String Base = "unassigned";//Defines the strength of the base if needed
String Polar = "unassigned";//Defines if the reactant is polarizable
String Solvent = "unassigned"; //Defines if the solvent is protic or aprotic
if ( Solubility == "yes" )
{
System.out.println("Is the functional group attached to a primary, secondary, or tertiary carbon?");
System.out.println(" Answer in p for primary, s for secondary, and t for tertiary.");
keyboard = new Scanner(System.in);
functional = keyboard.next();
switch (functional){
case "p": System.out.println("All unimolecular reactions are ruled out, leaving E2 and Sn2.");
System.out.println("Is the reactant a strong base? Answer in y for yes or n for no");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if (Base == "y" ){
System.out.println("The reaction undergoes E2");
} else{
System.out.println("The reaction undergoes Sn2");
}
break;
case "s": System.out.println("No reactions have been ruled out.");
System.out.println("Is the reactant a strong base? Answer in y or n");
keyboard = new Scanner(System.in);
Base = keyboard.next();
if( Base == "y" ){
System.out.println("yay");
} else {
System.out.println("whatever");
}
break;
case "t": System.out.println("tertiary");
break;
}
}
else{
System.out.println("No reaction will occur");
}
}
}
It's another one of those mistakes that you and I will make once in a while.
Short answer: You can't use == to compare strings!
Long answer:
In your if statements, you are comparing strings with ==. You should never EVER do that. The == compares the memory addresses of the two operands if they are not a primitive. I know you want to check if the characters of the two strings are the same. But two strings with the same characters may not have the same memory address!
What you should do is use the equals method to compare strings, like this:
if (Solubility.equals("yes"))
You can also use the equalsIgnoreCase method. It does what it says on the lid. Remember to change all the other if statements as well!
Moreover, you cannot use switch statements to switch a string. But seeing you didn't recieve any compiler error, I think you are using Java 8.
But if you are not using Java 8, the best way IMO to resolve this is to switch a Character.
char functionalChar = functional.charAt(0);
switch (functionalChar) {
case 'p': // remember to use single quotes!
...
}
Although this is not the biggest problem, it is still worth correcting:
You only need to instantiate Scanner once.
It is perfectly fine to use a switch statement for multiple input types - even within an if statement.
Your problem is that you keep re-initializing the Scanner object.
Once you have initialized the Scanner:
Scanner keyboard = new Scanner(System.in);
Then elsewhere where you would like to receive input, just re-use it:
//keyboard = new Scanner(System.in); // You don't need this line
Base = keyboard.next();
Also, the reason that you are never entering your if statement is the way you are comparing Solubility with'Yes'. For Strings, you should use either equals() or equalsIgnoreCase if case does not matter.
Change the if statement to the following line and your code will work as expected:
if ( Solubility.equalsIgnoreCase("yes"))

Checking if user entered anything?

I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}

Integer.parseInt(System.console().readLine() Cannot Handle Characters

Beginner Java enthusiast here.
I wanted to take a break from structured practice stuff and start with a blank page, and no help to write something of my own to test myself.
I had to learn about console().readLine() as I had not learned how to receive user input from the console. This lead me to parsing integers etc. I was able to build, and compile a program that did what I had envisioned, and did so perfectly! (if not a little clumsily...) However, I wanted to think outside the box, and see how I could use it in ways NOT intended and break it. Inputting anything but a number at the console (for instance typing P instead of 6) it throws an error because I only told it how to handle a number.
Long story short, I stretched past my knowledge and taught myself a lot, but could not find the answer I was looking for due to my lack of knowledge. If someone can even just tell me what to read up on, I am more than happy to do the learning myself, just need a nudge in the right direction.
Here is my program:
public class mysteryDoors{
public static void main(String[] args){
int doorOne = 1;
int doorTwo = 2;
int doorThree = 3;
System.out.println("Welcome contestant, to the Mystery Doors Game!");
System.out.println("Would you like to find out what is behind door number 1?");
System.out.println("Maybe door number 2?");
System.out.println("Or perhaps, door number 3?!");
int choice = Integer.parseInt(System.console().readLine("Please Choose a door..." ));
while (choice > 3){
System.out.println("I am sorry, please choose one of the available doors.");
int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
choice = guess;
}
if (choice == 1){
System.out.println("Behind door number 1 is a wonderful sofa set!");
}
else if (choice == 2){
System.out.println("Behind door number 2 is a nice shiny silverware set!");
}
else if (choice == 3){
System.out.println("Behind door number 3 is a NEW CAR!");
}
}
}
Why not use Scanner? Refer to: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner scanner = new Scanner(System.in);
int choice = in.nextInt();
AFAIK System.console() doesn't work in IDEs.
Use a try/catch block to handle exceptions, like so:
try
{
int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
choice = guess;
}
catch(NumberFormatException e)
{
System.out.println("Sorry, your input should be an integer. Try again.");
e.printStackTrace();
}

Java Scanner doesn't work in Processing

For an assignment I have due, my group and I were asked to code an educational/interactive game, and we decided on a basic maths one.
To get the users answers, we decided to use Java Scanner and put this line of code at the top of all the code we have;
java.util.Scanner
One of the loops that use this is the page with the questions on it, the loop looking something like this;
scoreCount = 0;
for (questions = 0; questions < 5;) {
//get the user's answer
userAnswer[questions] = input.nextInt();
//text box for users answer
if (userAnswer[questions] == compAnswer) {
//put tick next to answer
//add one to score
scoreCount = scoreCount + 1;
} else if (userAnswer[questions] != compAnswer) {
//put cross next to answer
}
//go to next question
questions++ ;
}
I'm working through all the errors that were thrown up and every time i don't have java.util.Scanner commented out Processing throws us the errors unexpected token: and then either class or void, which i don't get, but when java.util.Scanner is commented out, the classes and voids all work and the .input.nextInt() isn't recognised.
I am new to Java programming and Processing, any help at all would be greatly appreciated
EDIT
i think this is the link which lets you see my code, it's called Test;
https://github.com/MeganSime/Week8DataVis
you have to check if scanner has next int (token)
Scanner input = new Scanner(System.in);
.
.
if(input.hasNextInt()) { // or hasNext()
userAnswer[questions] = input.nextInt();
}
You're probably inserting a non int value where the scanner expects that. You should do something like that:
if(input.hasNextInt()) {
userAnswer[questions] = input.nextInt();
} else {
scan.next(); //consume any non-int value like ":"
}

Categories