Why does my evenOdd code produce an output? - java

I'm a first year university student starting my computer science major so sorry for any rookie mistakes. We've just gotten to if/else statements and practice mostly on this website called "Practice-It!", a coding practice website for Java, C++, and Python although I'm currently learning Java. Now, I recently got to this problem called "evenOdd" in which we need to read an integer from the user and print "even" if its an even number or print "odd" if it's an odd number. The exact problem goes as follows:
Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise. You may assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
I'm pretty sure I know how to do this, but when I enter in my bare code, it produces no output. I'm unsure of why. My code goes as follows:
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
    System.out.println("even");
} else  if (number % 2 != 0) {
    System.out.println("odd");
}
I should mention I'm supposed to put in bare code, meaning no class or methods.
I'm not sure if it's just me or maybe the website's slightly faulty. Any help is much appreciated.

Your code is sound, but if that is all the code you submit to the compiler then it won't work. You need to import the Scanner class from java.util.Scanner and you need to run your code inside a function and a class, unlike python which can run free in an IDE or console. Here is the code that worked for me.
import java.util.Scanner;
public class temp{
public static void main(String [] args){
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
System.out.println("even");
} else if (number % 2 != 0) {
System.out.println("odd");
}
}
}
Hope that helps.

I would suggest you use some IDE like Eclipse or NetBeans. These IDEs will help you in writing and debugging your code. They will also mark errors in your code and also provide description and quick fix which will help you code.
package abc.xyz.test;
import java.util.Scanner;
public class EvenOdd
{
public static void main(String... args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
if (input.nextInt() % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
input.close();
}
}
You can download eclipse from https://www.eclipse.org/downloads/ and NetBeans from https://netbeans.org/downloads/. Both of them are free, you don't have to pay anything for using them.

You need to import the scanner from java.util package. In every java program there must be a main method. try the following code. Look at my code i am creating an instance of Scanner named userInput and at the end of my code i am calling the close() method to prevent resource leak. you will not get any error for not closing but it is part of good practice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int number = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Type a number");
number = userInput.nextInt();
if( number % 2 == 0 ) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
userInput.close();
}
}

Related

Problems with Input and output regarding Java String

Well Hello,
I´m trying to program a kind of game in my free right now.
I started coding some time ago in school but recently we didn´t do much with java so I thought I should do something, so that I don´t forget everything. Well, I still need some since we never did something that's kind of like this. My Problem is that it shows an error and tells me an symbol is missing. The program is supposed to start the game and later interact with different types of objects that contain character information such as stats for both monsters and the player.
import java.util.Scanner;
public class Spiel{
public static void main(String[] args) {
System.out.print("What is your name Adventurer?\n ");
Scanner scanner = new Scanner(System. in);
String Abenteurername = scanner. nextLine();
System.out.println("Adventurer "+Abenteurername+" will you help us clean the dungeon? \n");
String Spielstart = scanner. nextLine();
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else
}
}
As you wrote ja without quotes, it expects to find a variable defined with that name, like
String ja = "ja";
if (Spielstart.equalsIgnoreCase(ja)) {
System.out.println("Gut");
}
But what you want is just
if (Spielstart.equalsIgnoreCase("ja")) {
System.out.println("Gut");
} else {
System.exit(0);
} // end of if-else

How to create a method that repeats a function?

Hello everyone I am new to the site and this is my first question from my Java programming class.
I have to create a program that asks a math question and tells the user if he is right or wrong, but the requirements also state that I need to create a method that generates a new question if the first question is correct, so when the computer asks what is 5 times 5 and the user inputs 25 the method should generate two new random numbers and ask the user for a result.
This is my code so far. I don't expect the answers as this is a school assignment but if anyone could give a direction it would be greatly appreciated it as this is my first java college course.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
}
while (answer != result);
}
I think you have the basic way that your loop statements work mixed up. A do statement is going to execute its block of code once and wont inherently loop on its own. A while loop will repeat until you tell it to stop. So without telling you exactly how to structure your assignment ;) you should look at those two things. But your code does compile and does do one run through of what you want it to do. So this means that the problem you have is in the logic aspect of your code. This means that the computer doesn't understand based on the structure of your code when to execute the sections of your code.
So my advice is to try writing it out in plain English first (pseudocode) that way you can work out how the logic of your program should run and then translate it into code. Sometimes just saying "I want x to happen when y. But I only want this to happen if event z has happened." can help you understand logical how something has to work.
Best of luck
You could add a while loop before the generation of the random numbers that would repeat until answer== "exit". Something along those lines would work fine
You should put a break; statement in the bottom else loop and put everything from your public static void declaration in an "infinite" for loop. When the user inputs an incorrect answer, the program will go to the else loop and break. Otherwise, it will keep on repeating in the "infinite" for loop. Here is a sample code showing what you could do.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
boolean loopTest = false;
while (loopTest= true)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from the user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
break;
}
while (answer != result);
}
}
}
*Note that the last } was not included in your program.

BlueJ and Input from keyboard

i have written the following code:
import java.io.*;
public class Typer
{
public static void main(String[] args)
{
Console cons;
cons = System.console();
boolean edition = true;
if(cons == null)
{
edition = false;
}
if(edition)
{
String name = cons.readLine("Give your name: ");
System.out.println("Your name is: "+ name);
}
else
{
System.out.println("There is no console!");
}
}
}
i am using BlueJ and it doesn't prompt for an input. it just prints out there is no console! Any thougts? Thanks you!
When i compile and run the program at powershell it runs normally. the thing is different with bluej for some reason.
To input any value using BlueJ, I normally use the BufferedReader statement.
It goes like this,
BufferedReader name=new BufferedReader(new InputStreamReader(System.in));
After writing this statement in the class or the method, you can input any value using the console.
Be sure to give this statement after asking for a value.
In case of integers-
int variable name= Integer.parseInt(name.readLine);
I think that BlueJ has a View>Console or a View>Output window. I am fairly certain of that, but it's been a long time since I used Bluej. Anyhow, You can use a Scanner object. The Scanner is a good way of handling input and I think it is more commonly used for input. It is a part of the Java API and examples of how to use it can be found here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
The code shown on the page is used to scan from a file, but the same approach can be used to get input from the console and then do something with that. When you run the code and wherever you see the output from the System.out.println call, the program should wait for you to enter something.

Using Scanner to change boolean in 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

Class, Interface, or enum expected error with exceedingly simple tester class

I'm having trouble finding out the reason im getting the expected class error. I have a class declared that houses just one main method but even when I comment out everything but the brackets I still get the same error. I've been looking at the four brackets for a while now, and can't seem to figure out what the problem is. How can i tell if two java files are in the same "package?"
Also, it's pointing to after my last bracket for where it thinks the error is.
EDIT: I decided to just write more code and now I'm getting a not a statement error on line 17 of my code. the integer declaration. I'm very confused as to what's happening
import java.util.Scanner;
public class BugTester
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int userMove;
char userDir;
Bug lady = new Bug(1,1,'E');
lady.draw();
lady.printCurrentPosition();
int continue=1;
while (continue ==1)
{
System.out.println("Please enter new Direction");
userDir = (char) System.in.read();
System.out.println("Please enter Distance to be moved");
userMove = in.nextInt();
lady.turn(userDir);
lady.move(userMove);
System.out.println("Again(0 to stop)?");
continue = in.nextInt();
}
}
}
You probably have an invalid invisible char at the end of file. You can go to the end with the cursor and then delete all chars after the last bracket. It has helped for me.
EDIT
Remark about your new code:
The word "continue" is a keyword in Java, you cannot use it as variable name.

Categories