So I only VERY recently got into what people call "coding", especially Java.
Here's what I've made with my teeny tiny hands. Basically, you input a year, and it converts it into centuries:
import java.util.Scanner;
public class somemaths {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a year:");
int str = sc.nextInt();
int calc1 = (str+99)/100;
if (str>0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
if (unity>=4)
System.out.print("th century. I'm sure of it!");
if (unity==3)
System.out.print("rd century. I'm sure of it!");
if (unity==2)
System.out.print("nd century. I'm sure of it!");
if (unity==1)
System.out.print("st century. I'm sure of it!");
}
else
System.out.print("Please don't input negative numbers :c");
}
}
Questions are:
1) Eclipse tells me that 'sc' is never closed. What is this about?
2) Is the code itself okay-ish?
3) This is probably the noobiest question I'll ever ask, but how can I create a window with a dialog and a text box (as in, a box where you can input some numbers), and then show the result in another dialog window? I've vaguely heard of JOptionPane.showMessageDialog before, but I just don't know how to apply it here.
Thanks a bunch!
You should try and focus your questions a bit more on Stack Overflow to get better answers. Asking three questions in one is expecting a lot. Also your second question is better suited to code review stack exchange. Your third question is also quite broad.
Question 1:
A Scanner object needs to be closed once you're finished with it. Call sc.close()
at the end of your program to do this.
Question 2:
Your variable names aren't as good as they could be. If you want to ensure your code is 'complete', you should look into unit testing and write a comprehensive suite of tests to ensure your code covers all cases. E.g. you will have a test case which takes the date 1980, and ensures the correct output of the 20th century is given.
Question 3:
You should look into Java Swing for creating a simple GUI. There are lots of tutorials out there.
sc is never closed
Since Scanners use input streams, they will open the stream to use them. They don't automatically close so to ensure safe and clean termination, after the last input from sc, call sc.close(). Technically since it's System.in nothing bad happens if you don't but you should close it anyway.
Is the code itself simple/complete enough?
Go to Code Review if your code works and you want to make it better in terms of efficiency, et cetera. However, I will tell you that you should probably be doing something like this:
if (str > 0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
String century;
if (unity == 1) century = "st";
else if (unity == 2) century = "nd";
else if (unity == 3) century = "rd";
else century = "th";
System.out.print(century + " century. I'm sure of it!");
else
System.out.print("Please don't input negative numbers :c");
}
JOptionPane#showMessageDialog
Official Documentation of javax.swing.JOptionPane
For your purpose, you probably want:
JOptionPane.showMessageDialog(
null, // This is the parent frame; if unspecified, it will make a new window
"the output goes here", // This is the output you want to show to the user
"some title" // You can specify the title
// This will use the defaults to display a notification (not an error or a confirm) with the default icon. Check the docs for more information
)
I've modified your java code to clean it up a bit. I'll provide some explanations as to what I changed an why I did so.
sc.close();
Your first problem is caused by not properly calling the close() method of the scanner object named sc. You can find some other helpful posts on stack overflow (such as this one) on why this is essential, but you will need to understand how your programs utilize memory and how the Scanner object in particular utilizes it. For now, I would just always make sure that you close all scanner objects once they are done being utilized.
if (unity>=4)
....
if (unity==3)
....
if (unity ==2)
....
Instead of using an if statement for each case of what the unity variable equals, you should be using either if else statements or a switch statement. In your program, you do not want any possibility of the other if statements executing. It might not seem obvious in your example, but if this type of code was within a much larger project, you or someone else could vary easily modify the unity variable in between one of your if statements and change the behavior of your output. This is a good practice to get into as you are learning to program, and is important once you start working on larger projects. Always ask the question, "What if 5 years from now someone looked at my code?" :) I would also try to follow a consistent "coding standard". Be consistent in your spacing and when to use curly braces. This makes your code much more readable.
import java.util.Scanner;
public class somemaths {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a year:");
int str = sc.nextInt();
sc.close();
int calc1 = (str+99)/100;
if (str>0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
if (unity>=4){
System.out.print("th century. I'm sure of it!");
} else if (unity==3){
System.out.print("rd century. I'm sure of it!");
} else if (unity==2){
System.out.print("nd century. I'm sure of it!");
} else if (unity==1) {
System.out.print("st century. I'm sure of it!");
} else {
System.out.print("Please don't input negative numbers :c");
}
}
}
}
Related
So recently I've switched over from python to java and was trying to recreate some of the projects that I made on python in java. The first thing that came to mind was a quiz.
Basically, to create a quiz, I define an answer variable to the answer then use the scanner method in java to detect the user's input. After that, I use an if statement to see if the input equals the answer.
ex.
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String answer = "dog";
System.out.println("What is a common furry animal");
String input = scan.nextLine( );
if (input.equals(answer))
{
System.out.println("Correct");
}
else
{
System.out.println("Inncorect");
}
}
}
Now that all works but the user doesn't know the exact casing of the answer variable which means if the variable was "dog" and he input "Dog" it would be incorrect. So if it was possible to create an "or" condition to an if statement it would be awesome if someone let me know.
-Thanks
To or any condition in Java, use the conventional || to separate conditions. In your case it would be something like:
if (input.equals(answer) || input.equalsIgnoreCase(answer))
Although you probably just need the Java method equalsIgnoreCase as the lone condition in the first place.
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"))
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
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;
}
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();
}