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

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

Related

How to generate multiple "Variables" in a list by Just entering the specific number of "Variables" asked to input

this is my first post here and I'm an aspiring programmer as well, so please when you see that I'm kind of talking nonsense don't go too harsh on me.
I'm having a bit of a problem creating a programme that I had in mind, this programme needs to ask the user for input on how many students are going to be marking, the user will insert a certain amount (example 10) after that is going to ask us to put for each of the 10 students a score in percentages.
what I had in mind was to create a For Loop to generate multiple “Variables” but I'm kind of lost on how I'm going to interact with each and one of them, so if you please could help me try to solve this problem that would be great, and please if there is a better way to do it please try to explain it to me as if you are trying to explain to a child. XD
The most simple way is just to use for loop for writting and for reading. I don't know why you need this but i hope it helps.
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i++)
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\n Procentages are: ");
for (int i=0; i<studenti;i++)
{
System.out.println(array[i]);
}
Best regards!
Blaz
So you definitely need an Array for this. There are several types you could use.
For you use-case the standard Array will do.
If you want to comply to object-oriented style, you should use a Student class. But I will do it with strings for now:
int numberOfStudents = 10;
String[] students = new String[numberOfStudents];
// now you can do:
students[0] = "John";
students[1] = "Michael";
// ...
// print all students
for(String student : students){
System.out.println(student);
}
Another way of doing this is with Lists. They are a bit more performance costly than arrays but are way more convienient to work with as you don't have to know how much entries it will have. Look at this:
import java.util.ArrayList;
ArrayList<String> students = new ArrayList<Students>();
students.add("John");
students.add("Michael");
// ...
// print all students
for(String student : students){
System.out.println(student);
}

I need help figuring out how to copy a person's response 100 times in a row

import java.util.Scanner; // *Has to be outside of brackets!*
public class Lab_1_3_Class_oops {
public static void main(String[] args) {
//I need to request a person's first and last name, then copy it on individual lines after they have entered their input
//Variables
Scanner sc = new Scanner(System.in);
//Requesting a name
System.out.print("Please write your first and last name.\n");
//Allowing a name input
sc.nextLine();
//I get as far as allowing text to be entered, but I can't figure out a way to keep that text in the memory long enough to get it copied 100 times without making the person type it 100 times
}
}
I am not looking for direct answers. I just want to know if what I want is possible with the way I have started and how I would even begin to try something like this.
Get the name input as a String and use a for loop to print it. I hope I wasn't too direct.
You need to declare a variable to hold the user's input. Then, you can use a for loop to do whatever you want any number of times.
String name = sc.nextLine(); // Declare a String variable to hold the value
for(int i = 0; i < 1337; i++) { // Use a for loop
// do something
}
Declare a variable to hold the user's input, then put it in a loop(print it from there)
Thank you all so much! The way I fixed it was by declaring
int num = 1;
and then creating a while loop
while (num <= 100) {
System.out.println(name);
num = num + 1;
}
I really appreciate everyone's help without actually telling me the answer.

Ask user to choose from array

I'm practicing Java and wanted to let the user choose an option from the Array such as:
String Food[] = {"Beans","Rice","Spaghetti"};
So far I only know of Scanner, but this is my first program so I don't know much of the subject.
Also, is there a way to print it? besides doing:
System.out.println(Food[0]); //and so on
for every single one of them.
Edit: not a Array list.
You can print the Array not ArrayList by doing:
System.out.println(Arrays.toString(Food));
It will print out: [Beans, Rice, Spaghetti]
If you are talking about an ArrayList, you would have to do:
ArrayList<String> Food = new ArrayList<String>();
Food.add("Beans");
Food.add("Rice");
Food.add("Spaghetti");
Then, you can loop over the ArrayList and build your own String with a StringBuilder
After reading your comment, I think you have a problem structuring your program. I will help you with that. Basically you have to complete these steps:
Program starts
Program outputs the options available in the menu
Program asks the user to choose one of the listed options
User chooses an option
Program will repeat step 3, only if the user wants to keep adding stuff to his order.
If the user does not want anything else, the Program outputs the total cost of the order
Some ideas of how to achieve this the right way:
I would use a class to encapsulate the characteristics of an "order". For instance: description, name, and price are important stuff that you need to be able to track per item.
when you don't know how many times your program will run, you have two options: using a do while loop or a while loop. Try to think in a condition that could make your program run indefinitely a number of times until the user is done. Inside the loop, you could have a sum variable where you would keep track of the items that the user wants.
It is better to keep track of items by just using numbers than Strings. Computers are faster to find stuff this way. So, if you use a HashMap to mock a database system in your program, it would make it better and faster. Then, instead of using if else to control your flow, you could use a switch instead.
I hope this helps.
EDIT: For a more efficient way of printing out the contents of the array, use an enhanced for-loop:
for(String f : Food)
{
System.out.println(f);
}
This is effectively the same as:
for(int i = 0; i < Food.size(); i++)
{
System.out.println(Food[i])
}
If I'm understanding what you're trying to do correctly, I think this should suffice (disclaimer, it's been a while since I've worked with Scanner():
public static void main(String[] args)
{
String[] food = {"Beans","Rice","Spaghetti"}; // Java standards are lowercase for variables and objects, uppercase for class names.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to eat? Options:");
for(String f : food)
{
System.out.println(f);
}
String response = in.next();
boolean validEntry = false;
for(String f: food)
{
if(response.equalsIgnoreCase(f))
{
validEntry = true;
}
}
if(validEntry)
{
System.out.println("You chose " + response);
}
else
{
System.out.println("Invalid entry. Please retry.")
}
}

Read keys from Properties file into array

I have an application that I have been working on. This application is configurable via a Properties file, from which it gets most of its variables.
This application is a survey, with the potential of any number of questions.
The questions are stored as an array, where the max index is equal to the number of questions.
I have tried the following:
for(int noOfQuestToSet = 0; noOfQuestToSet<noOfQuest; noOfQuestToSet++)
{
String[] questionArr = new String[noOfQuestToSet];
questionArr = props.getProperty("Q" + noOfQuestToSet).toString();
}
The idea is the loop will use an integer to compare to the number of emails noOfEmails variable (read from the properties file). The Question key syntax is Q1=<question>.
The loop should use an integer set to 0, compare it to the number of questions and append the number each increment to the array.
You need to explain more, what you are up to, and what your variables are.
What are the emails there for? and what is the Question key syntax? and how does getProterty() work.
and finally, what do you want to achieve? if you want an array with all the questions in it could look like this:
String[] questionArr=new String[noOfQuestToSet];
for (int i=0;i<noOfQuest;i++){
questionArr[i]=props.getProperty("Q"+i).toString();
}
If you dont know the exact number of questions in advance, use a List (ArrayList, or LinkedList) where you can add a string anytime without knowing the final size of the list.
plz read the guidelines for asking questions
for(int noOfQuestToSet = 1; noOfQuestToSet<=noOfQuest; noOfQuestToSet++)
{
int i = noOfQuestToSet -1;
questionArr = new String[noOfQuestToSet];
String appendToIndex = String.valueOf(noOfQuestToSet);
questionArr[i] = props.getProperty("Q"+appendToIndex);
String[] answers= new String[noOfQuestToSet];
do
{
Scanner scnAnswer = new Scanner(System.in).useDelimiter("\\n");
System.out.println(questionArr[i]);
answers[i] = scnAnswer.next();
if(iCheckAnswerforNull(answers, i)==true)
{
System.out.println("Please ensure you enter an answer to each question");
continue;
}
System.out.println(finalMess);
//EmailSend sendEmail = new EmailSend();
// EmailSend.sendEmail(userName, answers);
break;
}
while(true);
}
After a little tinkering and a shunt in the right direction from #meister_reineke, here is the working loop to get the property and append it to an array (without using ArrayLists:

Array setting length and storing information

This is homework. I'm trying to work with arrays and this is the first project working with them. My book shows all kinds of examples but the way they code the examples doesn't do any justice to what the assignment calls for.
I am trying to write a program that asks a user to enter students into the system. The program first asks how many you will enter then it will prompt you for the first name, last name, and score.
What I am trying to accomplish with this section of code is to ask the user how many students they will enter. The line of code that says
getStudentCount();
is a method that collects that information and then returns studentCount
I tried to code this to where the length of the array is going to be the number the user enters but it's not working so I wanted to ask for guidance. Ideally if this works and the user enters 3 then you will be prompted to enter the information 3 times. If the user enters 0 then the program doesn't ask you anything.
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application.");
int studentCount = 1;
getStudentCount();
studentCount = sc.nextInt();
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
{
Student s = new Student();
String firstName = getString("Enter first name: ");
s.setFirstName(firstName);
String lastName = getString("Enter last name: ");
s.setLastName(lastName);
int score = getScore("Enter score: ");
s.setScore(score);
}
}
Everything I had in the program worked up until I tried to code
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
which tells me there is something wrong with the way I am doing this.
Also the assignment asks that I store the information in the array. I'm not clear on how to call it or I guess store it.... I have another class with setters and getters. Is that enough to store it? How would I call it?
Again this is homework so any guidance is appreciated.
Thanks!
Well that's at least a homework example that shows some work on the part of the askee (and nicely written), so here's some help:
You set the studentCount to 1 and then call getStudentcount(), but never assigns the return value to your variable, hence the variable stays 1 (though you're overwriting it afterwards with sc.nextInt() which is probably not what you want if you already have a nice method for it). The fix is just to assign the return value of your method to the variable [1]
[1] Yes I know I shouldn't answer homework questions completely, but I really saw no way whatsoever to answer that only partially - proposals welcome though :)
My hints:
Look carefully at how you are getting the student count, and where you are putting it. You seem to be getting the count in two different ways, and that is at best redundant, and probably a bug.
Presumably there is a stack trace. Read it!!
The stack trace will tell you what exception was thrown, what its diagnostic message is, where it was thrown, and where in your code it was executing when the problem happened.
If you are having difficulty visualizing what is going on, use your Java IDE's debugger and single step the program.
Based on your follow-up comments, there isn't a stack trace. But if there was one, you should read it :-)
I don't understand your lines
getStudentCount();
studentCount = sc.nextInt();
if getStudentCount() "returns" the number they input (as you describe in your text), seems like you should be doing
int studentCOunt = getStudentCount();
I'm trying not to completely do your homework for you, but take a look at the code below for a glimpse of how to do this:
/* Some Declarations You're Going to Need */
private static Scanner scan = new Scanner(System.in); //Private, only need it in here
public static Student[] students; //Public, access it from any class you may need
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
System.out.print("Amount of students:");
int studentCount = scan.nextInt();
students = new Student[studentCount];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
System.out.print("Enter first name:");
String firstName = scan.next();
students[i].setFirstName(firstName);
System.out.print("Enter last name:");
String lastName = scan.next();
students[i].setLastName(lastName);
System.out.print("Enter score:");
int score = scan.nextInt();
students[i].setScore(score);
}
scan = null; //Done with scanner
}

Categories