How would I get a String from another class? - java

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

Related

How to put multiple programs into one class?

I have made two programs for an assignment. Now my professor wants me to put both programs into the same file and use a switch to create a menu where the user can use to choose what program they want to run. How do I do this? I will copy-paste both of my original programs below.
Program 1:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
String names = scanner.nextLine();
String[] namesSep = names.split(" ");
int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
}
}
Program 2:
import java.util.Scanner;
public class FindSmith {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type in your list of names: ");
String names = scanner.nextLine();
String[] namesSep = names.split(",");
for (int i=0; i<namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
}
}
You have two classes that do work in a single main() method each.
Start with: moving the content of that main() methods into another static method within each class, like:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
askUserForName();
}
public static void askUserForName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
...
}
}
Do that for both classes, and make sure that both classes still do what
you want them to do.
Then create a third class, and copy those two other methods into the new class.
Then write a main() method there, that asks the user what to do, and then
runs one of these two methods from there.
Alternatively, you could also do
public class Combo {
public static void main(String[] args) {
...
if (userWantsToUseClassOne) {
Readme.main(new String[0]);
} else {
FindSmith.main(...
In other words: as long as you keep your classes in the same directory, you can directly re-use what you already have. But it is much better practice to put your code into meaningful methods, like I showed first.
As you might know, each Java program only has a single entry point; defined by the method public static void main(String[] args). As each class can define this method only once and you have to specify the class the method is in in your META-INF.MF file, it is impossible to have multiple entry points.
So you have to implement the logic that controls the program flow and respects the user's choice on your own. You can e.g. ask the user via the command line what kind of subprogram they want to execute.
you can use multiple method instead of multiple class . and call all method from your main method should be solve your problem.....
public class Combo{
public void readName(){
// place here all code form main method block of ReadName class
}
public void findSmith(){
// place here all code form main method block of FindSmith class
}
public static void main(String[] args) {
Combo c = new Combo();
c.readName();
c.findSmith();
}
}
Rather than creating two classes, you can create single class with one main method. Where you can create 3 switch cases.
1) To call ReadName (RN)
2) To call FindSmith (FS)
3) To break the code (BR)
After every execution you can again call main method. (Optional) I have added that to continue the flow.
package test.file;
import java.util.Scanner;
public class Test {
private final static Scanner scanner = new Scanner(System.in);
//public class ReadName
public static void main(final String[] args) {
switch (scanner.nextLine()) {
case "FS" :
findSmith();
break;
case "RN" :
readName();
break;
case "BR" :
break;
default :
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
private static void findSmith() {
System.out.println("Type in your list of names: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(",");
for (int i = 0; i < namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
private static void readName() {
System.out.print("Please type in your full name: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(" ");
final int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
Welcome to this community! As #Stultuske comments, your better approach is convert your main methods to regular methods and invoke them depending on the user's input.
The steps you should follow are:
Join both main methods to a single class file.
Convert both main methods to regular methods:
Change their name from "main" to any other name. Usually, using their functionality as a name is a good practice. In your case, you can use the class names you already defined ("ReadName" and "FindSmith").
Remove their input parameter "args": as they are no more the main method of a class, they won't be reciving any args parameter, unless you specify it.
Define a new main method which reads from the scanner and call your new methods acordingly to the user input.

Creating a Java Method

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";
}
}

Error reached end of file while parsing

This is my Java class
import java.util.Scanner;
public class first {
public static void main(String args[]);
int right_number, user_input;
right_number = 6;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
user_input = input.nextInt();
if(user_input = right_number) {
System.out.println("That is the right number!");
}
else {
System.out.println("Aww, try again by typing java first into commad line.");
}
}
It keeps saying this:
Error reached end of file while parsing.
Can anyone help?
This is the first problem:
public static void main(String args[]);
You're not actually declaring a method body here. It should be:
public static void main(String[] args) {
// Method body goes here
}
You should only use a ; at the end of a method declaration for abstract methods (including those which are implicitly abstract in an interface). If you haven't got to abstract methods yet, just ignore that for the moment - basically use braces to provide a method body.
(The String[] args vs String args[] isn't a problem as such, but this version is preferred as a matter of style... as would naming your class First rather than first... there are various other style issues here, but I'll leave it at that for now.)
The fact that your class "tries" to end directly after an else statement should be a warning bell - an else statement can only appear in a method or constructor, so there has to be a brace to close that method/constructor and then a brace to close the class declaration itself. Likewise, the indentation should warn you of that - assuming you're using an IDE to perform the indentation, any time you find yourself writing method body statements which are only one level of indentation further than the class declaration, that suggests you have a problem somewhere - look up the file to see where it starts.
The code has a lot of mistakes like :
1.
public static void main(String args[]);
it should be
public static void main(String args[])
{
// every thing should be inside this
}
2.
You have declared your scanner object to be in , but you are doing user_input = input.nextInt(); , which should be user_input = in.nextInt();
3.
if(user_input = right_number) should say if(user_input == right_number) because = is the assignment operator, to compare you should use ==
This is the right code :
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int right_number, user_input;
right_number = 6;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
user_input = in.nextInt();
if(user_input == right_number) {
System.out.println("That is the right number!");
}
else {
System.out.println("Aww, try again by typing java first into commad line.");
}
}
}

An array only allowing certain values 0-9 & A-F for Java

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

How do I use object object1 = new object on my program?

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.

Categories