How do I initialize a result variable? - java

I need to make the result variable so that it is concatenated with my other strings to print my result and I tried multiple ways that are not working.
I have included my set of strings and first if statement to give an idea of my project.
My project rubric states "Initialize 'result' as a single string using concatenation. This string will contain the event type, party size, as as meal and preparation suggestions. Prints the result variable to the console." It also says " 'result' is a string that will be printed to the console.
import java.util.Scanner;
public class whatToEat {
public static void main (String[] args) {
int partySize;
String eventType;
System.out.println("Is your event Casual, Semi-Formal, or Formal?");
Scanner sc = new Scanner(System.in);
eventType = sc.next();
System.out.println("How many people will your event have?");
partySize = sc.nextInt();
if (eventType.equals("Casual") && partySize == 1) {
System.out.println("Since you're hosting a casual event for "
+ partySize +
" person, you should serve sandwiches prepared in the mircowave. ");

Because it says that 'result' is a string that you print in console, I suggest you saving your information in a String first:
String result = "";
Then:
result = "Since you're hosting a casual event for "
+ partySize +
" person, you should serve sandwiches prepared in the mircowave."
Finally:
System.out.println(result);

Related

Instead of displaying output after each iteration in my for loop, how to I get my program to display all outputs at once in java

I am new to coding and I wanted to know how can I code it so that I get the input question asked 3 times and then have my output displayed altogether in one message box. I want it to be kind of like:
Person 1's name is a
Person 2's name is b
Person 3's name is c
package example;
import javax.swing.JOptionPane;
public class Example {
public static void main(String[] args) {
for (int a =1; a<4; a++){
String name = JOptionPane.showInputDialog(null, "Enter person " + a + "'s name");
JOptionPane.showMessageDialog(null, "Person " + a + "'s name is " + name);
}
}
}
Declare a StringBuilder before for loop.
StringBuilder names = new StringBuilder();
Append each name inside loop with a suitable separator.
names.append("Person ").append(a).append("'s name is ").append(name).append("\n");
Then show the message dialog outside for loop with concatenated StringBuilder value

Program ends before scanner input object can be executed [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
My program is not working as it should.
Purpose of the code: ask user name, gender, age - if age over 18, ask user if married. if user says yes, output Mr or Mrs in front of already given name.
I'm practicing nested if statements and getter/setter methods to return private variables.
I have tried: nesting the if statement that tests the gender and age status, then i tried using a switch statement instead of an if statement to test the marital status, then i tried nesting an if statement within the switch to test the gender and age. I have tried giving each of the if, else if clauses their own scanner input thinking that would just get it to function, but it did not.
I originally had the marital status as a getter/setter method, but took it out to simplify the problem.
I have looked for an answer, but it seems like the code is right, it just will not take the input!
The code I have is as follows:
package agemessage;
import java.util.Scanner;
public class AgeMessage {
public static void main(String[] args) {
info infoObject = new info(); //setter getter class to house input from user
Scanner in = new Scanner(System.in);
System.out.println("what is your name again?");
String input = in.nextLine();
infoObject.getName(input);
System.out.println("thanks, " + infoObject.setName() + " is that a boys name or a girls name?");
String gender = in.nextLine();
infoObject.getGender(gender);
System.out.println("How old are you " + infoObject.setName() + "?");
int ageInput = in.nextInt();
//infoObject.getAge(ageInput);
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
//PROGRAM STOPS HERE -- DOES NOT EXECUTE INPUT
String status = in.nextLine();
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
}// main end
}//class end
OUTPUT:
run:
what is your name again?
Carrie Ann Moss
thanks, Carrie Ann Moss is that a boy's name or a girls name?
girl
How old are you Carrie Ann Moss?
40
Are you married yet?
BUILD SUCCESSFUL (total time: 16 seconds)
Right now you don't have a proper setter, add one and see if it works.
Please try putting in.nextLine(); after int ageInput = in.nextInt();
In this way the scanner will not ignore the next line after Integer.
A possible duplicate would be Using scanner.nextLine()
There are a few things that need to be addressed before we solve your problem.
Code conventions. These help others read your code. Not required, but it does help.
Getters and setters: A getter gets the object. A setter sets the object. You're using them in reverse. Example below.
class Person{
int age;
public void setAge(int a){
age = a;
}
public int getAge(){
return age;
}
}
So in a program, let's say we have a Person object, called annie, who is 22 years old.
Person annie = new Person();
annie.setAge(22);
Later in the program, we want to say how old she is...
System.out.println("Annie is " + annie.getAge() +" years old.");
The getter gets the value of the age variable on the Person object called annie.
Now for the actual problem in your program, when nextInt is called, it does not parse the newline character. So what is happening is this:
int ageInput = in.nextInt();
Here, when you enter "40" and then press Enter, you're giving the program this:
"40\n"
nextInt only reads to the end of the integer, so it only reads the 40, not the newline character.
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
This works correctly, printing out the "Are you married yet?" string.
However, it doesn't stop executing.
String status = in.nextLine();
Here's the problem. Your Scanner object, it hasn't passed beyond the previous newline character. So it immediately accepts the rest of the line, which is simply this:
"\n"
So the String status is then set to "\n".
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
Since status is set to "\n", nothing else is printed, and the end of the main function is reached, terminating the program.
To fix this, put a in.nextLine() directly after in.nextInt(). This skips the rest of the line, allowing your program to continue into the previously skipped sections.

Is it wrong to use a separate method for a scanner?

An exercise in the introduction to java programming book I am currently working through requires me to retrieve input from the command line using the scanner class. Each example in the book (and the code I have seen here) creates and uses a scanner object in the same method it is needed in, such as:
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter your first name: ");
String firstName = inputDevice.nextLine();
System.out.println("Enter your middle name: ");
String middleName = inputDevice.nextLine();
System.out.println("Enter your last name: ");
String lastName = inputDevice.nextLine();
inputDevice.close();
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
}
I was wondering why this method is preferred over something like the following (especially since the execise requires me to retrieve input for nine strings)
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
String firstName = prompt("Enter your first name: ");
String middleName = prompt("Enter your middle name: ");
String lastName = prompt("Enter your last name: ");
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
private static String prompt(String message) {
Scanner inputDevice = new Scanner(System.in);
System.out.println(message);
return inputDevice.nextLine();
}
}
Please keep in mind I am new to both Java and programming in general.
There's nothing wrong with doing it that way, and it very well may save you a few lines in the long run, but it's not common because you can create a Scanner once and reuse it, as you've done above.
It's all style-based, but using one Scanner multiple times is fairly straightforward and avoids unnecessary complexity in your code, which is important (especially in larger-scale projects).
When you're going through the code line-by-line, your first example is much more readable to me, but that's just my opinion, as this is a fairly subjective question. The only real downside is that you're creating a new Scanner every time you call the prompt() method, which is unnecessary.
Also note that you forgot to close the Scanner in the method.
In your case you are creating the Scanner object for every call of the prompt method which is not great practice.
Also you are not closing the Scanner.
IMHO the book's code is reads easier...

String concatenation in relation to JOptionPane

So, I haven't done any programming in a few months because I'm taking general prerequisite courses right now and I have a job, so now I'm a little rusty and I'd like to be up to par for when I take my next programming class in the Fall. Long story short, I'm trying to get back on track, so I'm making a silly practice program.
I made this program with all input and output done through the console using a Scanner, but then decided to go ahead and move over to JOptionPane as an interface. It was a pretty easy transition overall, but I'm just having a problem with the output at the very end. I'm trying to make all of the elements of an array into a nice, grammatically correct String for easy output in JOptionPane, but I can't really get my concatenation to work correctly. I realize that the output is not grammatically accurate when the amount of cats is one or two. I'll work on that after this, it's an easy fix.
Here is the code:
import javax.swing.JOptionPane;
public class JavaTestClass {
public static void main(String[] args)
{
//Get number of cats
int numOfCats = Integer.parseInt(JOptionPane.showInputDialog("How many cats do you have?"));
JOptionPane.showMessageDialog(null, "Oh, so you have " + numOfCats + " cats.\n", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
//Get cat's names
String[] catNames = new String[numOfCats];
for(int i=0;i<numOfCats;i++)
{
catNames[i] = JOptionPane.showInputDialog("Enter the name of cat " + (i+1) + ": ");
}
//Output cat's names
String catNameList = null;
for(int i=0;i<numOfCats;i++)
{
if((i+1) == (numOfCats-1))
{
catNameList.concat(catNames[i] + ", and ");
}
else if ((i+1) == numOfCats)
{
catNameList.concat(catNames[i] + ".");
}
else
{
catNameList.concat(catNames[i] + ", ");
}
}
JOptionPane.showMessageDialog(null, "So your cat's names are: " + catNameList, "Names of cats", JOptionPane.INFORMATION_MESSAGE);
}
}
Sorry about the spacing. It didn't really come out the way I wanted it to on here, but I don't have all day the indent all of the lines just for the sake of the post. Anyway, it should be relatively obvious, even without my long description above what I'm trying to do. Any help would be much appreciated. Thanks in advance.
Strings are immutable. Every operation that modifies a String returns a new one.
So it should be:
catNameList = catNameList.concat(catNames[i] + ", and ");
Also don't initialize it to null.
String catNameList = "";
Reference the String concat javadoc. Concat method is returning the result of concatenation.

how to invoke a method of a java class via command line while running program?

I'm trying to write a program for my self that will allow me to sort ArrayLists information of companies.
I don't want the program to always show me all the information, only about 8 different aspects of information at a time, such as market value, stock price, ceo, ect.. I have created a few common ones, but i wanted to create a way for the program to allow the user to create their own set of data for the program to display by inserting info. get(whatever command you want) system.
In other words, i want the program to allow me to input a method into the console and have it spit that method out. Is there anyway to do this that is simple?
Edit: Im still having trouble with this and the previous solution didnt actually work. So im going to show you exactly what im working with here:
public ArrayList<Object> newtag = new ArrayList<Object>();
ArrayList tagname = new ArrayList();
double tagnum;
int e = 0;
public void printCreate() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
System.out.println("Insert the number of tags you wish to view up to 5.");
tagnum = scan.nextDouble();
if (tagnum > 5){
System.out.println("Please enter a value less than or equal to 5.");
tagnum = scan.nextDouble();
} else {
for (int a = 0; a < tagnum; ++a){
++e;
System.out.println(e+". Insert the tag which you would like to look up:");
String taglookup = br.readLine();
newtag.add(taglookup);
System.out.println("Type the name of this tag that you would like to be displayed:");
tagname.add(br.readLine());
}
int c = 0;
for(Company info: companies){
if (tagnum == 1){
++c;
System.out.println("-------------------------------------------------------------");
System.out.println();
System.out.format("#%s. %5s Last trade: %s Days Low-High: %s - %s volume:%s \n", c, info.getCompanyName(), info.getRTLastTrade(), info.getDaysLow(), info.getDaysHigh(), info.getVol());
System.out.println();
System.out.println(tagname.get(0) + " : " + newtag.get(0));
System.out.println();
} else if (tagnum == 2){
++c;
System.out.println("-------------------------------------------------------------");
System.out.println();
System.out.format("#%s. %5s Last trade: %s Days Low-High: %s - %s volume:%s \n", c, info.getCompanyName(), info.getRTLastTrade(), info.getDaysLow(), info.getDaysHigh(), info.getVol());
System.out.println();
System.out.println(tagname.get(0) + " : " + newtag.get(0) + " " + tagname.get(1) + " : " + newtag.get(1));
System.out.println();
I need to essentially have it so that the newtag.get(0) becomes whatever the user wants from a list of information that all have getters. I tried using christans method but there is an issue with calling the different companies from the Company class.
The simplest way, is get an input of the name of the method, and check it in a if conditional, then call the respective method.
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if (choice.equals("nameOfMethod1")) {
nameOfMethod1();
} else if (choice.equals("nameOfMethod2")) {
nameOfMethod2();
} ...
You could also try a switch (available for String in Java 7)
switch (choice)
{
case "nameOfMethod1":
System.out.println("111");
break;
case "nameOfMethod2":
System.out.println("222");
break;
default:
break;
}
you could use java reflection framework to invoke a particular method on the object...you could create a wrapper.
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
No, the method needs to be compiled by the interpreter, this cannot be done on execution time.
If you want to call your method from command line excluding main() then at that time you can use Groovy a (REPL for a JVM lang).
You can try using command line arguments too.
public static void main(String[] args){
if (args[0].equals("METHOD1"))
callMethod1();
else if(args[0].equals("METHOD2"))
callMethod2();
else {
//Do other main stuff
}
}
You could use an interface to define how you're going to call the method, then instantiate one implementation of the interface for each name that you want to be able to interpret, and store the instances in a HashMap keyed by String.
I don't get your question.I think you wanna give an option to the user to giv input from the console application.
package MyExamples;
import java.util.Scanner;
public class GetInputFromUser {
public static void main(String args[]) {
int a, b, c;
Scanner input=new Scanner(System.in);
System.out.println("Enter first value =");
a = input.nextInt();
System.out.println("Enter second value =");
b = input.nextInt();
c = a + b;
System.out.println("Output is " + c);
}
}

Categories