I have an assignment where my program outputs a simple String using if conditions of another String, but I keep running into a problem where I cannot create a new instance(i think that is what it is called)
anyway, here is my code
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
**yesNoChecker check1 = new yesNoChecker();**
System.out.print(EP54.yesNoChecker);
}
public String yesNoChecker()
{
if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("OK");
else if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("Terminating.");
else
System.out.println("Bad Input");
}
}
Please help me! (bolded part is where I get error)
Can anybody give me a working version of the code so I can compare it with mine?
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
String answer = in.next();
yesNoChecker(answer);
}
public static void yesNoChecker(String in)
{
if(in.equalsIgnoreCase("y") ||
in.equalsIgnoreCase("yes") ||
in.equalsIgnoreCase("Sure") ||
in.equalsIgnoreCase("why not"))
System.out.println("OK");
else if(in.equalsIgnoreCase("n") ||
in.equalsIgnoreCase("no") ||
in.equalsIgnoreCase("nope") ||
in.equalsIgnoreCase("quit"))
System.out.println("Terminating.");
else
System.out.println("Bad Input");;
}
}
Got it
yesNoChecker() is a function, not an object. In this case you will want to invoke yesNoChecker() (also known as "calling the method"), rather than instantiate yesNoChecker (also known as "creating an object"). Instead, your code should look something like:
import java.util.Scanner;
public class EP54
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? ");
yesNoChecker();
System.out.print(EP54.yesNoChecker);
}
public String yesNoChecker()
{
// (omitted for brevity)
}
}
You instantiate new objects of a class type. For example, Scanner is a class that you've used here that Java provides you with. When you say new Scanner(), you are creating a new instance of the Scanner class.
yesNoChecker is a method, not a class-you cannot instantiate it.
You can call it:
yesNoChecker();
However, it is defined to return a String, which it currently does not do. You may want to return the string you are now printing instead.
You need to get the actual input from the user/Scanner class also.
Something like:
String s = in.nextLine();
Then you compare the String s to whatever you need ("Y", "yes" etc...)
Hope this helps!
p.s. Your function does that, but consider if someone enters a digit rather than a letter or a work. It is always a good idea to validate input before using it.
Related
import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
I want the user input from this class and
bring into another class and use the number variable for a
If statement
I want the user input from this class and bring into another class and
use the number variable for a If statement.
It is simple take a look at below example(make sure to add both classes in one package different java files as Player.java and ExampleClass.java),
This is the class that Scanner has:
import java.util.*;
public class Player{
public static void main (String [] args){
Scanner getInput = new Scanner(System.in);
System.out.print("Input a number");
//you can take input as integer if you want integer value by nextInt()
String number = getInput.nextLine();
ExampleClass obj = new ExampleClass(number);
obj.checkMethod();
}
}
This is the class that check number:
public class ExampleClass{
int number;
public ExampleClass(String number){
try{
//If you want to convert into int
this.number = Integer.parseInt(number);
}catch(NumberFormatException e){
System.out.println("Wrong input");
}
}
public void checkMethod(){
if(number > 5){
System.out.println("Number is greater.");
}else{
System.out.println("Number is lesser.");
}
}
}
Few thing to mention:
Your example code contains syntax errors, fix those first.
If you want integer you can use getInput.nextInt() rather than
getInput.nextLine().
You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
Use proper naming convention.
In my example I convert the String into integer inside the constructor and wrap with try-catch block to prevent from NumberFormatException(If you input character or something you can see wrong input will print). Sometimes in variaus situation it is not good to use try-catch in constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.
Where you normally make an import on the other class, just import the Player class and it should work
I'm not sure if I got it, I suppose you're using a scanner.
This is the way I would do that:
Scanner class:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insert a decimal:");
String inputValue = scanner.nextLine();
if(!new ScannerCalc().isNumeric(inputValue)){
System.out.println("it's not a number...");
break;
}
else
new ScannerCalc().checkNumber(inputValue);
}
}
}
ScannerCalc class:
public class ScannerCalc {
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
public void checkNumber(String number){
if(Integer.parseInt(number)%2==0)
System.out.println("it' even");
else
System.out.println("it's odd");
}
}
Pay attention on instantiation of classes to reuse methods.
If you want to make use of a local variable in another entity, it is better to pass it as an argument to a method of the other entity. For example
OtherClass.operation(scanner.nextLine()); // In case method is static
new OtherClass().operation(scanner.nextLine()); // In case method is not static
I am creating a java program that runs in tie with another file to help create what is called Object oriented programming.
So I have the whole program completed but I am having a hard time understanding how to make it compile and run. I know my problem is within the name of the method. However I dont quiet understand how to know what to call the method. From what I read there is several different types you can call it.
(Also I know the indentation looks messed up, it's right in my actual program)
Here is what I am looking at to help make sense of my question:
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main(String[] args)
{
class getUserChoice
{
System.out.println("Would you you like to play rock, paper scissors?");
userChoice = in.nextLine();
while (!userChoice.equalsIgnoreCase("Rock") && !userChoice.equalsIgnoreCase("Paper") && !userChoice.equalsIgnoreCase("Scissors"))
{
System.out.println("Invalid entry please try again");
userChoice = in.nextLine();
}
userChoice = userChoice.toUpperCase();
return userChoice;
} //end of UserChoice
class getCPUChoice
{
computerRandom = r.nextInt(3)+1;
if (computerRandom == 1) cpuChoice = "Rock";
else if (computerRandom == 2) cpuChoice = "Paper";
else if (computerRandom == 3) cpuChoice = "Scissors";
}
class pickWinner
{
//tie
if (userChoice.equals(cpuChoice))
{
winner = tie;
}
//user has rock
if (userPlay.equals("rock"))
{
if (cpuChoice.equals("Scissor"))
{
winner = user;
}
else if (cpuChoice.equals("Paper"))
{
winner = Computer;
}
else if (cpuChoice.equals("Rock"))
{
winner = tie;
}
}
if (userPlay.equals("Paper"))
{
if (cpuChoice.equals("Scissor"))
{
winner = Computer;
}
else if (cpuChoice.equals("Paper")
{
winner = tie;
}
else if (cpuChoice.equals("Rock")
{
winner = user;
}
}
if (userPlay.equals("Scissors"))
{
if (cpuChoice.equals("Scissor"))
{
winner = tie;
}
else if (cpuChoice.equals("Paper")
{
winner = user;
}
else if (cpuChoice.equals("Rock")
{
winner = computer;
}
}
}
}//end of RockPaperScissors
}
My error I get is:
RockPaperScissors.java:10: error: expected
System.out.println("Would you you like to play rock, paper scissors?");
Which from what I understand is from not having the class setup up right. Could someone maybe help explain how you know what to name each method correctly?
Thanks!
You can't declare more than one public class in a file
To fix the problem, remove the word public.
However I dont quiet understand how to know what to call the method.
As for this, to call a method, simply use the method name (full example of my answer):
public static void main(String[] args) {
class something{
public void someMethod(int argument){
//this doesn't do anything
}
}
something s = new something();
s.someMethod(1);
}
This isn't valid Java. You don't create a class to get choices; make it a method.
public class RockPaperScissors {
private static final String [] choices = { "ROCK", "PAPER", "SCISSORS" };
private Random random;
public RockPaperScissors() { this(null); }
public RockPaperScissors(Long seed) {
this.random = (seed == null) ? new Random() : new Random(seed.longValue());
}
// An Enum would be better than a number or String
public String nextChoice() {
return choices[this.random.nextInt(choices.length)];
}
}
Classes and methods can be defined inside other classes, but neither can be defined inside methods (functions), with the exception of anonymous functions. If this is a standalone program you intended to write, and you intended for getUserChoice and getCPUChoice to be methods, just remove the class keyword before both names and perhaps replace them with static if you want them to be static methods of your RockPaperScissors class. Methods need to have a return type and in your case, it can be String. You would still need to invoke either method in your main method.
I would imagine this is the sort of structure you are looking for in a "standard" program. You can declare other classes in other files and import those too. Your code will generally run in methods within those classes and is all called from the main method which is your entry point.
//imports here
public class ClassName {
public static void main(String[] args) {
//main entry point to your program
}
private String methodName(String param1) {
//do some stuff here
return someValue;
}
}
You can't create several classes in a single file. So it should have only one "class" keyword here.
Your methods are not well formatted, you should take a look at the Java Oracle Tutorial to get started with Java :)
Here is a simple example of class + method :
public class MyClass{
//Attribute
public int myMethod(int x) {
return x+1;
}
}
A method is defined by its visibility (public), the returned type (int), its name (myMethod) and its parameters (int x). So here your methods have a "class" returned type, which is not possible.
It seems like you are trying to write some kind of a guess game between a user and a computer...nice but less easier than it sounds.
As many have said you are having trouble because you are declaring classes with a wrong visibility and not exactly at the right place
The names you gave your two classes gives me the feeling they should be methods rather than classes. So It would be simpler two have three methods.
The main method: that's where you run your game loop
A getUserChoice(): that's where you ask the user to input its choice (Good that you block the user until he inputs a valid choice)
The getCPUChoice: That's where you ask the cpu to input his choice
Some one the variables you use will necessarily be shared between more than one method, so declare them at the class level so that they can be accessible wherever necessary. For example:
public class RockPaperScissors {
static String userChoice = "";
static String cpuChoice = "";
static Scanner in = new Scanner(System.in);
static Random r = new Random();
// ... rest of the code here
You should instantiate your Random object and declare your computerRandom variable before using them.
Just as a practical illustration I created a game loop (there are often infinite :)) in the main method where I receive the user's input and the computer input and then compare then. Success comes with a congratulation and failure with a try again note. I am not assuming that it is exactly where you were trying to get, but it could be.
Here is my complete illustration code
import java.util.Scanner;
import java.util.Random;
/**
* Created by alompo on 07.11.16.
*/
public class RockPaperScissors {
static String userChoice = "";
static String cpuChoice = "";
static Scanner in = new Scanner(System.in);
static Random r = new Random();
public static void main(String[] args) {
while(true) {
getUserChoice();
getCPUChoice();
if (cpuChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Good choice, you have a match with the computer");
} else {
System.out.println("Sorry mismatch between you and the computer...try again");
}
}
}
public static void getUserChoice()
{
System.out.println("Would you you like to play rock, paper scissors?");
userChoice = in.nextLine();
while (!userChoice.equalsIgnoreCase("Rock") && !userChoice.equalsIgnoreCase("Paper") && !userChoice.equalsIgnoreCase("Scissors"))
{
System.out.println("Invalid entry please try again");
userChoice = in.nextLine();
}
} //end
public static void getCPUChoice()
{
int computerRandom = r.nextInt(3)+1;
if (computerRandom == 1) cpuChoice = "Rock";
else if (computerRandom == 2) cpuChoice = "Paper";
else if (computerRandom == 3) cpuChoice = "Scissors";
}
}
First of all and before posting my question let me ask you people to stop downvoting my questions even if they seem stupid to you ,this site is an important place for me, it helps me a lot with my java doubts which are many,a question ban would be an heavy setback for me, so be helpful even by not answering!
Now for the question,
I have this method were i assign a value to a setter method with user input
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
this method is later called in main from object p1 and object p2 and being assigned a differend value for each one to the instance variable name
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
but when i call the getName() method at the end of main both p1 and p2 have the same value!
Shouldn't each object get it´s own copy of an instance variable?
The Problem is in your addName()-function. Your running your loop(while (!answer.equals("y") || (!answer.equals("n")))) until a y or n is entered. So as soon as you enter it, your loop will stop.
In your loop your checking if the input that was made cotains a y or n. Now the problem should be clear. Your loop won't run with those two values entered, but inside the loop you want to check if one of those is entered.
Two little personal hints(everyone has another style): Don't use break; let your loops end themselfs. Do it with an boolean-variable and updating it's state.
The second hint would be to use one Scanner-Object. For example you could add a Scanner-parameter to your addName-function. Just init one in your MainClass.
Those hints and fixes of the problem applied to your code could look like that:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
And your MainClass:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Hope that helps!
I created a JAVA code, and I don't have any errors, but when I run the code, the output does this:
Enter a word: Thank you for entering a word! And it does not let me enter anything, when I intend for the code to let me enter a word, then it checks if it is a word, and gives the answer if it is a word, or none if it isn't. (It is my first time asking on this site) Here's the code:
package files;
import java.util.Scanner;
public class Testprinter {
static boolean myBoolean = false;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.toString();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
public static boolean checkInput(String usersInput){
if(usersInput == (String)usersInput)
{
return true;
} else { return false; }
}
public static void checkifComplete(){
if(myBoolean = true){
System.out.print("Thank you for entering a word!");
}
}
}
This line is wrong:
if (usersInput == (String)usersInput)
It should be:
if (usersInput.equals(usersInput))
In Java, strings (and in general: all objects, that is all types that are non-primitive) must me compared using the equals() method, which tests for equality. The == operator is fine for testing equality between primitive types, but for objects it tests for identity - a different concept, and 99% of the time, not what you want.
And besides, you're comparing a string with itself! it'll always return true, I'm quite sure that's not what you want to do… notice that the parameter must have a different name, currently it's called just like the attribute. Perhaps this is what you meant?
public static boolean checkInput(String input) {
return usersInput.equals(input);
}
You forgot scanner.nextLine(); thats reason its not asking you enter anything.
Instead of usersInput = userInput.toString();
Use:
String usersInputStr = scanner.nextLine();
Follow this link - for how to use scanner: How can I read input from the console using the Scanner class in Java?
Your issue is using userinput.toString(), when you should be using usersInput = userInput.next();. You are currently retrieving the string representation of the scanner, not getting a word.
Corrected main:
public static void main(String[] args){
String usersInput;
while(myBoolean != true)
{
System.out.print("Enter a word: ");
usersInput = userInput.next();
myBoolean = checkInput(usersInput);
}
checkifComplete();
}
Full working now and code is complete Thanks for the help.
You can restrict user to enter another value by this: (This program is for if You are taking values from user). This will asks for number until you enter number within 0 to 9.
You can make your code according to this. (This is just for your reference, How can you restrict user to enter wrong thing)
Scanner scan=new Scanner(System.in);
int i=-1;
i=scan.nextInt();
while(i<=0 && i>=9){
i=scan.nextInt();
}
EDIT
As per your comment, In that case you need to change this as:
String s="";
while(!s.matches("^[0-9A-F]+$")){
s=scan.nextLine();
}
I would create a class to hold the RGB values and have it check that the correct values are entered. See the test code below.... you can expand as you need to handle more cases.
import java.util.*;
public class jtest
{
public static void main(String args[])
{
new jtest();
}
public jtest()
{
ArrayList<RGB> RGBarray = new ArrayList<RGB>();
try
{
RGBarray.add(new RGB("F"));
RGBarray.add(new RGB("J"));
}
catch(BadRGBValueException BRGBVE)
{
BRGBVE.printStackTrace();
}
}
class BadRGBValueException extends Exception
{
public BadRGBValueException(String message)
{
super(message);
}
}
class RGB
{
public RGB(String input) throws BadRGBValueException
{
if (!input.matches("^[0-9A-F]+$"))
{
throw new BadRGBValueException(input + " is not a valid RGB value");
}
value = input;
}
private String value = null;
}
}