Changing an object's value according to user Input - java

I am trying to figure a way in how to change an object's value. I've made a class in which it contains set and get for the object and 3 sorts of values being PRICE, QUANTITY and NAME.
The price and name are already set in the test class
System.out.println("How many would you like?");
String quantity = s1.nextLine();
quantity = food1.setQuantity();
quantity = food1.setQuantity(); is wrong. How do I change it according to how much quantity the user wants?

You may try with:
quantity = food1.setQuantity(Integer.parseInt(quantity));
instead of:
quantity = food1.setQuantity();

I don't mean to sound harsh, but programming isn't magic. Look at what you're doing:
String quantity = s1.nextLine();
quantity = food1.setQuantity();
You're overwriting the string with what one would hope to be a void set method. Instead, the method should be a void set method, which accepts an integer, so you would do the following (assuming proper function implementation):
String quantity = s1.nextLine();
food1.setQuantity(Integer.parseInt(quantity));
Not sure if you learned Exception handling yet, but you should wrap this in a try/catch if you have. If not, you can use regular expressions to see if it's an integer, if that is necessary. Odds are this is a class assignment, and you're probably assuming that the input is valid or using exception handling. Good luck.

Assuming, that the quantity is supposed to be an integer, you could write this:
String quanity = s1. nextLine();
//check that quanitity is a valid number before trying to parse it as a number
if(quantity.matches("\\d+"))
{
food1.setQuantity(Integer.parseInt(quantity));
}else
{
System.out.println("The quantity you entered is not a valid number.");
}

Related

Am trying to recall the output of line 8 but still having problems

am trying to refer back to line 8 but don't know how, sorry am new to Java.
I've tried many approaches but still hitting a wall, pls what should I do.
package Interview;
import java.util.Scanner;
public class Interview {
public static void main(String[] args) {
System.out.println("hello,please what is your name:");
System in = scanner(System.in);
String Input=in.nextLine();
System.out.println("well then welcome to startechz "+Input);
System.out.println("Are you a male or female:");
String Input=in.nextLine();
if (Input=male)
//recall outprint from line 8
System.out.println("once again, welcome mr"+Input of Line8);
else {
System.out.println("once again,welcome mrs"+Input of Line8);
}
}
there many syntax error on your code it would be better to use ide
change this
System in = scanner(System.in);
to
Scanner in = new Scanner(System.in);
you can not redefine same variable again you have to statement
that looks like this
String Input=in.nextLine();
to solve this either use this
String newInput=in.nextLine();
or just assign new value to the same variable (of course of course if you do not want to use the old one again) like that
Input=in.nextLine();
in java to compare value you use double = sign like
Input==male
single = are used to assign value like int value = 5;
you can use == with primitive type only it will work but for reference type it will not work as in your case you use String with is reference type
why it did not work with reference type cause it will compare the reference address (the address for the object in memory (to be accurate it not the physical address but think of it like that))
so use the equal method
like
if (Input.equals("male")) // you forget also to make male as string you forget the double quotations
Change
if (Input=male)
to
if(Input.equalsIgnoreCase("male")) // allows case independent compare
Use equals or equalsIgnoreCase to compare strings.

Is there a way to show an error message while the user has not entered a valid value, within the condition of a while loop

I pretty new to java programming so i was wondering if there is a way to use the condition of a while loop to stop an invalid value being used.
I am writing a program that prompts the user to enter an identification number as an integer then uses a scanner to store that value.
Just wanted to know if this is possible to put something in the condition of the for loop that prints an error message if the enter something like a string, double or char so i dont get the Input Mismatch Exception.
like this:
identification = userId(in); //scanner
while (identification (is not an integer)){
System.out.println("Invalid Value, Please enter an integer");
identification = userId(in);
Even better, you can write:
while ((identification = userId(in)) < 0) {
System.out.println("blah ...");
}
The assumption is that the userIn method returns some negative value if the input is not an integer. You can make the invalid return value whatever you want as long as it is not something that is a valid input.
Some people don't like this style because it has gone out of fashion and they are not used to it; however, it used to be common in C programming and there is nothing about it that is implicitly unclear or bad.
This should do what you are asking. It is basically a while loop that waits until the next input is an integer before continuing the code. The important part is making sure to use in.next() inside the while loop instead of in.nextInt() because the values could be anything.
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!(in.hasNextInt()))
{
System.out.print("Integer not entered, please enter an integer: ");
in.next();
}
int value = in.nextInt();
System.out.println("The int was " + value);
in.close();

How to get corresponding data from different arrays

I have 2 arrays that have corresponding data, one has 20 names and another 20 grades, Im asking the user to enter a name and then taking the name and matching it up to the grades file and returning the grade, how would I go about doing that.
Ive tried doing something like this then returning g which refers to grade and getName refers to the name input from the user. Also getName is a string and g is an int array.
getName.length() = g.length;
Would I have to scan through the grades file to find that exact line with the corresponding grade? Im not really sure how to achieve this.
Since your question does not provide the relevant data, I'll try to answer your question with my own variable names, and you can cross check my code with yours.
Assuming the names are stored in the String array names[], and the marks are in the int array marks[], and getName contains the name to be found,
int FoundMarks = 0;
for(int i = 0; i < names.length; i++)
{
if(names[i].equalsIgnoreCase(getName))
{
FoundMarks = marks[i];
break;
}
}
System.out.println("Marks of "+getName+": "+FoundMarks);
This is a simple Linear Search which takes each individual name of names and checks if the user is searching for that particular one. If found, then the marks of that person is stored in FoundMarks, and the looping stops.
This type of searching algorithm will be incredibly useful in almost all array related operations.
I repeat, the variable names might be different than yours, but the core logic remains the same.

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

Having trouble with calculations... what's wrong?

Having trouble calculating this out. The rest of the coding is fine but this one class. The error focuses on one line.
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
The errors tell me that "class expected" "; expected" and "not a statement". Where am I going wrong because this seems correct to me?
private class CalcButtonListener implements ActionListener
{
// The actionPerformed method executes when the user clicks the calculate button
public void actionPerformed(ActionEvent e)
{
double retail_price;
String input1;
String input2;
//Get the number from the users input in priceFeild1
input1 = priceField1.getText();
//Get the number from the users input in priceFeild2
input2 = priceField2.getText();
// Calculate out the operation below to find the retail_price
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
JOptionPane.showMessageDialog(null, "The retail price of the item is: $" + retail_price );
}
The name of the class containing parseDouble is Double, not double. They are not synonyms. double is the name of the primitive type, and primitives do not have methods.
So you need:
retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);
However, you should also strongly consider using BigDecimal instead of Double anyway, as that's a better match for currency values.
Additionally, I'd recommend:
Following Java naming conventions, using camelCase instead of underscore separators
Giving your variables more meaningful names - what are input1 and input2 meant to represent? A price and a discount, perhaps?
Declaring variables only where you need to, rather than at the start of the method
Considering what you want to happen if the value entered by the user isn't a valid number
Considering whether you care about internationalization (e.g. a user entering "10,50" instead of "10.50". If so, look at NumberFormat and DecimalFormat
Try:
Double.parseDouble(input1)
parsing of double retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);

Categories