ArrayList with if statements - java

I am tasked with creating a simple Turing Test using ArrayLists. I know how to create the ArrayLists, but I'm having trouble connecting them to the if statements to respond properly to the user input. An example of this issue is below. When the user inputs Frank I want the first response, and any other input should result in the other response. However, whatever tweaks I make just make one or the other show up no matter what I input.
List<String> names = new ArrayList<>();
names.add( "Frank" );
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if( names.contains( "Frank" )) {
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}
else {
System.out.printf( "What an interesting name. My name is John.\n");
}
**Having another issue. For the second question I'm trying to use an else if statement. However, when I respond with the else if response, it gives me the final else response of "I would have never guessed" every time.
System.out.print("Where are you from? ");
states.add(scanner.next());
if (states.contains("Florida") || states.contains("florida")) {
System.out.println("So was I!\n");
} else {
if (states.contains("North Carolina") || states.contains("north carolina")) {
System.out.println("I hear that's a nice place to live.\n");
}
else {
System.out.println("I would have never guessed!");
}
}

Try the following:
List<String> names = new ArrayList<>();
System.out.print( "Hello, what is your name? ");
names.add(scanner.next());
if(names.contains( "Frank" )){
System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}else{
System.out.printf( "What an interesting name. My name is John.\n");
}
I removed the part where you add Frank to the array. This way the results might be a little different depending on your input. I still find it a little strange that you are using an ArrayList. It seems like just saving a simple variable could do the same thing.
With an ArrayList it is possible however that you could have previous answers affect other answers.

Related

Convert years to centuries - How to improve it/Run it

So I only VERY recently got into what people call "coding", especially Java.
Here's what I've made with my teeny tiny hands. Basically, you input a year, and it converts it into centuries:
import java.util.Scanner;
public class somemaths {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a year:");
int str = sc.nextInt();
int calc1 = (str+99)/100;
if (str>0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
if (unity>=4)
System.out.print("th century. I'm sure of it!");
if (unity==3)
System.out.print("rd century. I'm sure of it!");
if (unity==2)
System.out.print("nd century. I'm sure of it!");
if (unity==1)
System.out.print("st century. I'm sure of it!");
}
else
System.out.print("Please don't input negative numbers :c");
}
}
Questions are:
1) Eclipse tells me that 'sc' is never closed. What is this about?
2) Is the code itself okay-ish?
3) This is probably the noobiest question I'll ever ask, but how can I create a window with a dialog and a text box (as in, a box where you can input some numbers), and then show the result in another dialog window? I've vaguely heard of JOptionPane.showMessageDialog before, but I just don't know how to apply it here.
Thanks a bunch!
You should try and focus your questions a bit more on Stack Overflow to get better answers. Asking three questions in one is expecting a lot. Also your second question is better suited to code review stack exchange. Your third question is also quite broad.
Question 1:
A Scanner object needs to be closed once you're finished with it. Call sc.close()
at the end of your program to do this.
Question 2:
Your variable names aren't as good as they could be. If you want to ensure your code is 'complete', you should look into unit testing and write a comprehensive suite of tests to ensure your code covers all cases. E.g. you will have a test case which takes the date 1980, and ensures the correct output of the 20th century is given.
Question 3:
You should look into Java Swing for creating a simple GUI. There are lots of tutorials out there.
sc is never closed
Since Scanners use input streams, they will open the stream to use them. They don't automatically close so to ensure safe and clean termination, after the last input from sc, call sc.close(). Technically since it's System.in nothing bad happens if you don't but you should close it anyway.
Is the code itself simple/complete enough?
Go to Code Review if your code works and you want to make it better in terms of efficiency, et cetera. However, I will tell you that you should probably be doing something like this:
if (str > 0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
String century;
if (unity == 1) century = "st";
else if (unity == 2) century = "nd";
else if (unity == 3) century = "rd";
else century = "th";
System.out.print(century + " century. I'm sure of it!");
else
System.out.print("Please don't input negative numbers :c");
}
JOptionPane#showMessageDialog
Official Documentation of javax.swing.JOptionPane
For your purpose, you probably want:
JOptionPane.showMessageDialog(
null, // This is the parent frame; if unspecified, it will make a new window
"the output goes here", // This is the output you want to show to the user
"some title" // You can specify the title
// This will use the defaults to display a notification (not an error or a confirm) with the default icon. Check the docs for more information
)
I've modified your java code to clean it up a bit. I'll provide some explanations as to what I changed an why I did so.
sc.close();
Your first problem is caused by not properly calling the close() method of the scanner object named sc. You can find some other helpful posts on stack overflow (such as this one) on why this is essential, but you will need to understand how your programs utilize memory and how the Scanner object in particular utilizes it. For now, I would just always make sure that you close all scanner objects once they are done being utilized.
if (unity>=4)
....
if (unity==3)
....
if (unity ==2)
....
Instead of using an if statement for each case of what the unity variable equals, you should be using either if else statements or a switch statement. In your program, you do not want any possibility of the other if statements executing. It might not seem obvious in your example, but if this type of code was within a much larger project, you or someone else could vary easily modify the unity variable in between one of your if statements and change the behavior of your output. This is a good practice to get into as you are learning to program, and is important once you start working on larger projects. Always ask the question, "What if 5 years from now someone looked at my code?" :) I would also try to follow a consistent "coding standard". Be consistent in your spacing and when to use curly braces. This makes your code much more readable.
import java.util.Scanner;
public class somemaths {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a year:");
int str = sc.nextInt();
sc.close();
int calc1 = (str+99)/100;
if (str>0) {
System.out.print("This is the " + calc1);
int unity = calc1%10;
if (unity>=4){
System.out.print("th century. I'm sure of it!");
} else if (unity==3){
System.out.print("rd century. I'm sure of it!");
} else if (unity==2){
System.out.print("nd century. I'm sure of it!");
} else if (unity==1) {
System.out.print("st century. I'm sure of it!");
} else {
System.out.print("Please don't input negative numbers :c");
}
}
}
}

How to store a value for later use? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a new user and I have a "noob" question. We are being taught Java in school and I have a question about one of our activities. One requirement is to take in student info (such as course) and convert them to a single letter (I assume use .charAt??) and then later on count how many students are enrolled into that course. I have the student info down here:
import java.util.*;
import java.lang.*;
public class CourseTallier
{
public static void main (String[] args)
{
String student = inputStudInfo();
}
public static String inputStudInfo ()
{
Scanner kbd = new Scanner(System.in);
int limit = 0, idnum = 0;
String college = "";
System.out.println("Please input a valid ID number:");
idnum = Integer.parseInt(kbd.nextLine());
if (idnum == 0)
{
System.out.println("Thank you for using this program.");
System.exit(0);
}
while (idnum < limit) {
System.out.println("Invalid ID number. Please enter a positive integer:");
idnum = Integer.parseInt(kbd.nextLine());
}
System.out.println("Please enter a valid course (BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
while(!college.equalsIgnoreCase("BLIS") && !college.equalsIgnoreCase("BSCS") && !college.equalsIgnoreCase("BSIS") && !college.equalsIgnoreCase("BSIT"))
{
System.out.println("Invalid course. Please enter either BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
}
return college;
}
public static Character convertCourse (String college)
{
}
and as you can see I am stuck at the "Convert Course" method (modular is required). I was wondering how would I convert something like "BLIS" to a single character "L" and then create another method that counts the number of how many students are enrolled in that course.
I am not asking for someone to complete this program for me cause that would be cheating. I am simply asking someone for a shove in the right direction. Your help is very much appreciated.
Edit: As asked here are the exact requirements:
Program
To the storing for future values, do you know what instance variables are? Unless I misunderstood the question, it seems like it would make sense to make four (static) instance variables that hold the count of users enrolled in each course.
You could either use the .charAt method or use the "switch" statement.
the problem with the charAt method is that you probably can't find different letters for each course using the same indexed letter.(which will bring you to the switch statement again)
To count the number of student enrolled in that course you should have a count variable and increase it every time you convert a course into a single char.
One way would be to use a switch statement
switch(college)
{
case "BLIS":
return("a");
}
Not sure if thats really what your meant to be doing, if your meant to store student data then a Map implementing datastructure would be the go
Well, first of all you need to make your code more modular. How about dividing it into sections,like, getting user input, validating user input, storing user input.
Well to store the user data, you can use something like a HashMap. Keep course as key (eg BLIS) and no of students as value. In start intialize it with 0.
Map<String, Integer> studentCourseHashMap = new HashMap<String, Integer>();
studentCourseHashMap.put("BLIS", 0);
So, every time a user enrolls for the particular course all you need to do is to find the course and increment it by 1. So, for example if a student enrolled for BLIS course. then,
if(studentCourseHashMap.containsKey("BLIS")){
//Checking if BLIS course is available
Integer noOfStudents = studentCourseHashMap.get("BLIS");
//Increment no of students for each enrollment
noOfStudents++;
//Saving the updated value in hashmap
studentCourseHashMap.put("BLIS", noOfStudents);
}
Hope this will help, mention your doubts in comments. :)
why not use a counter for each course and increment it whenever the user enters it.
switch(college)
case BLIS:
blisCounter+=1;
break;
case BSCS:
bscsCounter+=1;
break;
case BSIS:
bsisCounter+=1;
break;
case BSIT:
bsitCounter+=1;
break;
If you want to take each letter from the string, here's the way:
String str = "BLIS";
String strArray[] = str.split("");
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}
If you want to map the Course String to individual Characters, below is the way:
Map<String, Character> courseMap = new HashMap<String, Character>();
courseMap.put("BLIS", 'L');
courseMap.put("BSCS", 'C');
courseMap.put("BSIS", 'S');
courseMap.put("BSIT", 'T');
for(String courseStr: courseMap.keySet()) {
System.out.println(courseStr + " > " + courseMap.get(courseStr));
}

Array Response Output

So I'm working on a little fun project that'll ask you a series of questions, and depending on what you respond with, give a specific output. Well, I've gotten all the way to the first output answer, but I can't figure out what to do.
Here's the source code. I can't seem to get the code input into the question correctly.
import java.util.Scanner;
public class Questionaire {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answers[] = new String[1];
String response[] = new String[5];
System.out.println (" Good Evening, Devin. How are you today? ");
answers [0] = in.nextLine();
response [0] = "I'm good";
response [1] = "I'm okay";
response [2] = "I'm alright";
response [3] = "I'm great";
response [4] = "good";
if (answers[0].equals (response.length)) {
System.out.println (" That's awesome! What would you like to talk about?" );
}
else {
System.out.println( " Oh, well then.." );
}
}
}
OUTPUT:
Good Evening, Devin. How are you today?
I'm okay
Oh, well then..
Basically, I'm trying to get the if statement to take the whatever the user inputs into the answer[0] array, and if they respond with any of the responses in the response array, they get the first system.out, but whenever I type in any of them, I keep getting the else output. Can anyone tell me what I'm doing wrong?
You want to find the match of the user input from response array.
if (answers[0].equals (response.length)) will never evaluate to true unless the user input is 5 because you are comparing user input with response.length which value is 5. You need to loop from each element in response
or simply change
if (answers[0].equals (response.length))
to
if(Arrays.asList(response).contains(answer[0]))
you will need to add import java.util.Arrays
answers[0].equals (response.length)
This code will be false as answer[0] is string matching with response.length which is 5. if you want to check the answer with the response exist then code need to be modify as below
Boolean checkresponse=false;
for(int i=0;i<response.length;i++){
if (answers[0].equalsIgnoreCase(response[i])) {
System.out.println (" That's awesome! What would you like to talk about?" );
checkresponse=true;
break;
}
}
if(checkresponse==false)
System.out.println( " Oh, well then.." );

How can I use a method in one class to create an instance of another in Java?

I have two classes, one that is a computational object (CyberPet.java) and the other that tests the computational one (TestCyberPet.java). In the TestCyberPet, I have a method called createPet() that will use user input to instantiate an instance of CyberPet. I've already done
CyberPet pet3 = null;
This is createPet():
private static CyberPet createPet()
{
/*** Local variables ***/
Scanner scanner = new Scanner( System.in );
final String formatString = "%22s: ";
String name;
String size;
String activity;
/*** Get user input ***/
System.out.println();
System.out.printf( formatString, "Enter your pet's name" );
name = scanner.nextLine().trim();
System.out.println();
System.out.printf( formatString, "Enter your pet's size (big or small)" );
size = scanner.nextLine().trim().toLowerCase();
System.out.println();
System.out.printf( formatString, "Enter your pet's current activity (eating, sleeping, or thinking)" );
activity = scanner.nextLine().trim().toLowerCase();
/*** Validate input, notify user of errors ***/
if ( name.length() == 0 )
{
System.out.println( " Invalid input. Name cannot be blank." );
name = CyberPet.DEFAULT_NAME;
}
// else leave as entered string
if ( size == "big" || size == "small" )
{
System.out.println( " Invalid input. Size must be either big or small." );
size = CyberPet.DEFAULT_SIZE;
}
// else leave as entered string
if ( activity == "eating" || activity == "sleeping" || activity == "thinking" )
{
System.out.println( " Invalid input. Activity must be eating, sleeping, or thinking." );
activity = CyberPet.DEFAULT_ACTIVITY;
}
// else leave as entered string
/*** Create cyberpet ***/
CyberPet pet = new CyberPet( name, size, activity );
return pet;
}
I've got it working (I think!) up until I try to do this
pet3.createPet();
Because createPet isn't in the CyberPet class to use it there. How can I use createPet to create an instance of CyberPet?
I hope I put enough information in here... This is my first post on StackOverflow, so if I need to add anything more, just tell me! :)
Well, it seems that you've got a bit of a mixed up understanding of how these classes should be.
If you're creating a test object, then you shouldn't need user input. You should just use known values. It's quicker and serves the same purpose. Secondly, if you want to access a private static method, then you need to do so from within the class. It can be accessed via:
TestCyberPet.createPet();
This will return an instance of type CyberPet.
Note
Firstly, you need to look at testing frameworks like JUnit. This automates the testing process for you and makes it easier to write these sorts of tests.
Secondly, revise your knowledge of OOP. You should not be performing validation of user input for a class, outside of that class. Only the class itself should know what it needs.

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.

Categories