How to initialize a string array in a main Java method - java

I have written some code which creates and initializes a String ArrayList. Is it possible to declare the arguments directly in to the String [] args method itself, rather than creating an extra String arrayList?
public class sampleCode{
public static void main(String[] args ) {
String[]args2 = {"en", "es"};
if( args2[0].equals("en")) {
System.out.println("english option");
}
else if( args2[1].equals("es")) {
System.out.println("spanish option");
}
else System.out.println("this is the default option");
}
}

Firstly, It was difficult to understand your request, but I get it finally.
The answer of your request is YES. Yes it is possible to not create an extra array of String in your code. In this case, you need to enter the options en and es using the command line.
Here is how to update your code:
public class SampleCode {
public static void main(String[] args ) {
//String[]args2 = {"en", "es"};
if( args[0].equals("en")) {
System.out.println("english option");
}
else if( args[1].equals("es")) {
System.out.println("spanish option");
}
else { System.out.println("this is the default option");}
}
}
Now, here is the process:
In your terminal, compile your code : javac SampleCode.java
And execute it by giving the arguments: java SampleCode "en" "es"
It is a possible manner to do what you need. But in this case, english option will always be obtained.
Hope, it helps you.

Related

How to deal with an unitialized constructor in an if statement (Java)

I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.

JUnit test for void method (output-input dependency)

I came up with a problem while trying to write a JUnit test for one specific method.
I searched for possible solutions but many of them were not helpful as the output was not dependent on the input. Any help would be much appreciated.
My class method looks like this:
public static void method1() {
Scanner input = new Scanner(System.in);
String state = input.nextLine();
if( /* condition dependent on state value */ ) {
System.out.println("...");
} else {
System.out.println("..."+state+"...");
}
}
How to write a JUnit test for it, can Robot class somehow solve the problem?
If you extract the logic to a separate function like
public static void method1() {
Scanner input = new Scanner(System.in);
String state = input.nextLine();
System.out.println(processingLogic(state));
}
static String processingLogic(String state) {
if ( /* condition dependent on state value */) {
return "some value";
} else {
return "some other value";
}
}
you can write a unit test for that function to see that it works correctly.
You can manipulate System.in and System.out using System.setIn() etc. For instance
System.setIn(new ByteArrayInputStream("test data".getBytes()));
However, I have the feeling that for your case, changing your method in a way that #p-j-meisch suggested in https://stackoverflow.com/a/59513668/2621917 is much better.

Calculate length of first argument in java

I want to print the length of the first argument(args[0]) but getting ArrayOutOfBountException :
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
When you write the code,
public class Main {
public static void main(String[] args){
args[0] = "Hello";
System.out.println(args[0].length());
}
}
At this point args[0]="Hello";, If your args a String array is not initialized then, while execute I'm supposed to think that you may have used the command in such a way java Main to execute your basic program.
Which cause the error, You have not passed any argument through command line so your String[] args is not initialized yet and it is not able to store your String "Hello" inside array args[0] and you are trying to print an empty array and throw the Exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.main(Main.java:3)
Update Answer:
Now Yes, You can use that to verify the String args length before print.
public class Main {
public static void main(String[] args){
if(args.length !=0){
System.out.println(args[0].length());
}else{
args = new String[1]; //Initilize first
args[0] = "Hello"; //Store value in array element
System.out.println(args[0].length()); //Print it.
}
}
}
First, check if there is an argument. Then print the length. It's not a good idea to change the values in the argument array either. Something like
if (args.length > 0) {
System.out.println(args[0].length);
} else {
System.out.println(0);
}
should do it.
Here array of String does not have any initialized objects and args has 0 element. That's why it is recommended to check whether does args have any element or not. Then, proceed further accordingly. This is how code looks like.
public class Main {
public static void main(String[] args){
if(args.length !=0){
// do something
}else{
// args doesn't have element.
return ;
}
}
}
You need to check first if an argument is even present.If there is no argument passed and you try to access any element, it will throw ArrayIndexOutOfBoundsException. Also, you should avoid assign any hardcoded value to the elements in array. The code to access 1st element can be something like below:-
if(args.length>0){
System.out.println(args[0].length());
}

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

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