can't pass user input to main in method call - java

I am trying to write a simple program where user enters username and password at the command line. Program check user input if valid if yes, it displays Welcome whatever the name is. Program also check password valid. I couldn't find a way to call checkCommandLine in main and pass user input to it. Any advise?
public class HelloWorld3 {
public static boolean checkCommandLine(String [] args){
if (args.length == 1)
{
//If the string is blank “ “ then display error message
if (args[0].trim().isEmpty())
{
System.out.println("args[0] is null");
return false;
}
return true;
}
//If args does not contain a string then display an error message
else if (args.length == 0)
{
System.out.println("args[0] doesn't contain string");
return false;
}
return true;
}
public static final String Password = "abc123";
public static boolean checkPassword(String uPassword){
if (uPassword.equals(Password)){
return true;
} else {
System.out.println("Password invalid");
return false;
}
}
public static void main (String[]args){
//to receive the command line arguments
//call checkCommandLine
//if all ok the say welcome username
if (checkCommandLine(new String[] {"A", "B"})){
System.out.println("Welcome" + " " + "A");
}
//call checkPassword
//if valid then say from within main, your password is good
if (checkPassword("abc123")){
System.out.println("Your password is good");
}
//if not ok, then say password invalid
}
}

In the main method you can pass the command line arguments like this:
public static void main (String[]args){
checkCommandLine(args);
....
}
For passing the command line arguments you can refer http://www.javatpoint.com/command-line-argument

You can pass the args of main method just like Agrawal did.
If so, you can execute it from cmd as follows
java HelloWorld3 yourID abc123
else use Scanner to get the input during your code

Related

Return statement continues to prompt user to input String

The aim of my program is to take input of an attribute of an animal and then print the animal that has a corresponding attribute. I've used setter and getter methods along with three other methods that create the correct characteristics of the animals and then check if the attribute inputted corresponds with the animal.
My issue is that my input() method that's supposed to return the inputted String will run once if you put in an attribute corresponding to the first animal, but if you input a attribute corresponding to the second or third animal it will re-prompt you two or three times respectively, and once the program does find the correct animal it will just continue to re-prompt the user until for input. Like this:
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
You can have a Parrot
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
You can have a Parrot
Enter one attribute you'd like in your pet: green
You can have a Parrot
Process finished with exit code 0
I'm not sure why this is happening or how to fix, all I need is the input prompt to happen once and then print the correct animal to the user. Any help would be greatly appreciated, thanks. My current code is this:
import java.util.*;
class Main {
private static String name;
private static String colour;
private static String personality;
private static String noise;
public String input(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter one attribute you'd like in your pet: ");
String input = sc.next();
return input;
}
public void setName(String name) {
this.name=name;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setPersonality(String personality) {
this.personality = personality;
}
public void setNoise(String noise) {
this.noise = noise;
}
public String getName(){
return this.name;
}
public String getColour(){
return this.colour;
}
public String getPersonality(){
return this.personality;
}
public String getNoise(){
return this.noise;
}
public void PetOne(){
Main petOne = new Main();
String input = input();
petOne.setName("pug");
petOne.setColour("tan");
petOne.setPersonality("playful");
petOne.setNoise("woof");
if(input.equals(petOne.getName()) || input.equals(petOne.getColour()) || input.equals(petOne.getPersonality()) || input.equals(petOne.getNoise())){
System.out.println("You can have a Pug");
} else PetTwo();
}
public void PetTwo() {
Main petTwo = new Main();
String input = input();
petTwo.setName("cat");
petTwo.setColour("brown");
petTwo.setPersonality("affectionate ");
petTwo.setNoise("meow");
if(input.equals(petTwo.getName()) || input.equals(petTwo.getColour()) || input.equals(petTwo.getPersonality()) || input.equals(petTwo.getNoise())){
System.out.println("You can have a Cat");
} else PetThree();
}
public void PetThree() {
Main petThree = new Main();
String input = input();
petThree.setName("parrot");
petThree.setColour("green");
petThree.setPersonality("intelligent");
petThree.setNoise("squawk");
if(input.equals(petThree.getName()) || input.equals(petThree.getColour()) || input.equals(petThree.getPersonality()) || input.equals(petThree.getNoise())){
System.out.println("You can have a Parrot");
} else throw new RuntimeException
("Attempt to use real attributes n/0");
}
public static void main(String[] args) {
Main m = new Main();
m.PetOne();
m.PetTwo();
m.PetThree();
}
}
Try calling the input() method from main() and saving the result as a String which you refer to in the Pet() methods. Your input could be saved as a global variable or passed around as a parameter. This will avoid asking for the same input many times over.
Also, run your program in debugging mode and go through it line by line to ensure you understand why it is currently asking the user for the input so often. Debugging can be good for learning as well as fixing :)

Build the initial version of a word list processing application

I have a question in regards to the following questions.
Now in question 1 down below it wants to create a java class.
Create a Java class called Words with the following contents:
import javax.swing.JOptionPane;
public class Words {
public static void main(String[] args) {
WordList ws = new WordList();
String in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
while (in != null) {
ws.addWord(in);
in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
}
JOptionPane.showMessageDialog(null, "Word list = " +
ws.toString());
JOptionPane.showMessageDialog(null, "First word = " +
ws.getFirst());
JOptionPane.showMessageDialog(null, "Last word = " +
ws.getLast());
}
}
In question 2 it asks the following:
Create a Java class called WordList in your existing Practical1 project with the following contents:
Right-click in the source code window of the class Words and select "Run File". Enter several words, clicking OK after each one and observe how the program behaves.
Make sure you understand how the application works.
In the class WordList, modify the methods getFirs and getLast as described by the associated comments. The associated comments are down below here from the WordList.java class:
import java.util.ArrayList;
public class WordList {
private ArrayList<String> theWordList = new ArrayList<String>();
public void addWord(String s) {
theWordList.add(s);
}
public String getFirst() {
// Replace the return statement below with a statement
// that returns
// the first word of theWordList (the word at index 0).
// Hint: use the ArrayList method "get".
// If there is no first word (theWordList has no words in it),
* "-" should be returned.
//
return "junk";
}
public String getLast() {
// Replace the string "junk" with the
// last word of theWordList (the word
// at index size()-1). Hint: use the ArrayList method "get".
// If there is no last word (theWordList has no words in it),
// "-" should be returned.
//
return "junk";
}
public String toString() {
return theWordList.toString();
}
}
The main questions I am more stuck in is with the comments they have left me in steps to completing question 4. How can I do these questions here??
In case you need the other class which is the main class, here it is and its labeled Words.java:
import javax.swing.JOptionPane;
public class Words {
public static void main(String[] args) {
WordList ws = new WordList();
String in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
while (in != null) {
ws.addWord(in);
in = JOptionPane.showInputDialog(
"Click cancel to end or enter a word and click OK");
}
JOptionPane.showMessageDialog(null, "Word list = " +
ws.toString());
JOptionPane.showMessageDialog(null, "First word = " +
ws.getFirst());
JOptionPane.showMessageDialog(null, "Last word = " +
ws.getLast());
}
}
How to get the contents from an ArrayList
For the first element in public String getFirst() {
if (theWordList.isEmpty ()) {
return "-";
return theWordList.get (0); // first element of List
For the last element in public String getLast() {
do the same empty check as above and then return
using theWordList.size () -1

How to initialize a string array in a main Java method

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.

Cannot make Scanner String method work

I'm trying to create a Scanner method for strings that returns the value entered by the user only if it is not blank (whitespace, user hitting 'enter' immediately etc..). If the user does this I want to print out an error message and have the loop return to the beginning again and await a new user input. If correct, I want the method to return the correct input value.
My code is as such:
private static final Scanner scr = new Scanner(System.in);
private static String readString(){
while(true){
String command = scr.next();
if(command != null && !command.trim().isEmpty()){
return command;
}
System.out.println("You have to type something");
}
}
Right now when I run this method in other methods if I leave a blank or simply hit 'enter' my output simply leaves a blank space until I type a string such as 'abc'. Then it returns that value.
Any helpful advice is appreciated!
Replace src.next() with src.nextLine()
private static final Scanner scr = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(readString());
}
private static String readString() {
while (true) {
String command = scr.nextLine();
if (command != null && !command.trim().isEmpty()) {
return command;
}
System.out.println("You have to type something");
}
}

How to fix a word requesting program?

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

Categories