Problems with Input and output regarding Java String - java

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

Related

Why does my evenOdd code produce an output?

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();
}
}

When I create a class, I receive "illegal start of type" error in "try-catch" block

class address
{
String address;
String newaddr = address.trim();
final int ziplength =4;
String input;
Scanner in = new Scanner(System.in);
String temp = in.next();
String zipcode = input.substring(input.length()-ziplength);
try **//illegal start type error**
{
Integer.parseInt(zipcode);
System.out.println("PO is: "+zipcode);
}
catch( Exception e) **//illegal start type error**
{
System.err.println("Last 4 chars are not a number.");
}
}
This code segment extract the last four characters from a string, and see if they are post code.
I have commented the point reporting "illegal start type error" in NetBeans.
I wonder, if I cannot use try-catch when creating a class? Or, do this class miss something?
I tried searching stackoverflow. But I am still confusing. Here are some links.
Java illegal start of type
Java error: illegal start of expression
java: Why does the program give "illegal start of type" error?
Java does not allow you to simply put statements in the body of a class. You always need an enclosing "block" around those statements.
In other words: the easiest way to a first working example would be to add a main method to your class and to move your code in there. Meaning a method with signature public static void main(String[] args)
Beside that: don't "wait" until several errors come together. Start with an empty class. Enter one new construct in there. Save; run the compiler. Go for the next "element" that you need.
For a beginner, your strategy (lets write 10, 20 lines of code; and then lets hope it works) will not work at all. You are wasting your time (and ours) by doing it like that. You see, this is so basic stuff that you should not turn to other people to explain them to you. You should start small and figure all these things yourself. Because that is the essence of learning programming.
class address
{
String address;
String newaddr = address.trim();
final int ziplength =4;
String input;
Scanner in = new Scanner(System.in);
String temp = in.next();
String zipcode = input.substring(input.length()-ziplength);
public address() //this is the only thing I add, but it eliminate "illegal start type error"
{
try
{
Integer.parseInt(zipcode);
System.out.println("PO is: "+zipcode);
}
catch( Exception e)
{
System.err.println("Last 4 chars are not a number.");
}
}
}
Special thank you for #Jägermeister . He gives me valuable hint.
Since I am a beginner, I am thinking a better way to improve my skills. I will try more.

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

Java Scanner Take Input, call a method, then back to read more input not working

I have a class called PlayGame, and in the main method I have this chunk of code:
public class PlayGame {
public static void main(String args[]) {
while (true) {
System.out.println("Where would you like your adventure to begin? (Enter a number)\n");
System.out.println("1. Play the Game\n2. Quit the Game");
Scanner userInput = new Scanner(System.in);
String userAction;
try {
userAction = userInput.nextLine().trim();
if (userAction.equals("1")) {
pressPlay();
} else if (userAction.equals("2")) {
System.exit(0);
} else {
System.out.println("Sorry, your selection wasn't valid.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This is all fine, and when the user types 1, pressPlay() is called and it proceeds to the next method which does some stuff, mainly printing things to the screen. However, when I leave the pressPlay() method and return back to this main method, I start getting errors for reading the Input:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at PlayGame.main(PlayGame.java:17)
Can you clue me in into how I can get around this? Much appreciated!
EDIT - I just want it to return to the while loop in the main method and ask for 1 or 2 again, and take a valid 1 or 2. My code goes all the way through to userAction = userInput.nextLine().trim(); without waiting for anymore user input the second time round, after leaving the pressPlay() method.
EDIT - The pressPlay() method produces a grid that the player is able to move around in by typing particular commands. It has a while (true) { loop inside of it, as well as Scanner userInput = new Scanner(System.in); which takes the players input. If the player types quit, it calls a break out of the while loop and returns back to the main method, where the problem then arises.
I've managed to fix the issue.
In both my main method and my pressPlay() method, I was creating separate scanners taking input from System.in, and this was causing problems as it would no longer take input from the main method. Instead I took the Scanner out of the main method and put it after public class PlayGame {, and used this same scanner in both of my methods, rather than separate ones.
Thank you Jayamohan and Hossam for your input (:

Categories