Sentinel number in if statement - java

For data structures and algorithms in java class I've been assigned to create a program that takes user input for an item's name and price and then averages the price. I have successfully done that, however, I am having a great deal of trouble on a certain specification for the program: a sentinel number (-1) that terminates the project. Here is my code, I will explain what the issue is after.
while(true){
System.out.print("Enter item " + (count + 1) + " name: "); // enter name
names[count] = in.next(); // next string becomes count index
System.out.print("Enter item " + (count + 1) + " price: "); // enter price
prices[count] = in.nextDouble(); // stores price entered as array index
if(prices[count] == -1) break; // if next price == -1 // the code i want to change.
if(names[count].equalsIgnoreCase("peas")) flag = true;
average += prices[count];
count++;
}
So, my issue is: I want to terminate the program when I enter -1 for the item name, not have to enter a "dummy" item name and then have to enter the sentinel number (-1).
Sorry for the long explanation, just trying to be thorough.
Thanks for taking the time to read this and help a programmer hopeful out.

You need to use a String for your comparison (but "-1" will do). Also, do it immediately after you get the input. Something like,
names[count] = in.next();
if (names[count].equals("-1")) {
break;
} // ...

Related

How to accept multiple inputs with Scanner function and the input meeting the if statement?

I'm creating a small project to improve my coding skills. So the problem I'm having is that I have an enroll method, which will allow the 'Student' to enroll into available courses. I put all the courses available in the enum class called 'Courses'.
The problem I am having is how do I get multiple inputs, and for every input if it meets one of the if statements it gets to added to an arraylist called 'enroll'. Otherwise if the user does not want to enroll the user has to type 0, to which I expect the next line to be read.
I think if you were to read my code you'd have a better idea in what I'm trying to do.
I have conducted research on how to get multiple inputs and split it, but that does not seem to work for me.
public int enrolled() {
System.out.println("The following courses available are:\n" + "1." + Courses.COMPUTERSCIENCE101 + "\n" + "2." + Courses.CHEMISTRY101 + "\n" + "3." + Courses.ENGLISH101 + "\n" + "4." + Courses.HISTORY101 + "\n" + "5." + Courses.MATHEMATICS101);
Scanner CS = new Scanner(System.in);
Scanner CI = new Scanner(System.in);
Scanner EL = new Scanner(System.in);
Scanner HT = new Scanner(System.in);
Scanner MM = new Scanner(System.in);
if(CS.nextInt() == 1) {
this.enroll.add(Courses.COMPUTERSCIENCE101);
} else if (CS.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(CI.nextInt() == 2) {
this.enroll.add(Courses.CHEMISTRY101);
} else if (CI.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(EL.nextInt() == 3) {
this.enroll.add(Courses.ENGLISH101);
} else if (EL.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(HT.nextInt() == 4) {
this.enroll.add(Courses.HISTORY101);
} else if (HT.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
if(MM.nextInt() == 5) {
this.enroll.add(Courses.MATHEMATICS101);
} else if (MM.nextInt() == 0) {
System.out.println("Course added and now exiting...");
}
System.out.println(this.enroll.size());
return this.enroll.size();
}
So it is expected that if the user wants to pick course 1,3,5. Those courses will be added to an arraylist. and should return the length as 3. However, it's allowing the user to input more than 5 inputs, if I was to include 0 as an input (user needs to only 5 inputs, e.g (1,0,3,4,5) or something similar where the returned size of the arraylist would be 4).
Maybe you should try a different approach. You could ask the user to type the code of the courses they want to join like this:
Scanner in = new Scanner(System.in);
System.out.println("The following courses are available:");
System.out.println("Computer Science 101, Course code: CS101");
System.out.println("More courses...");
System.out.println("Type Q to end.");
String input = in.next();
while (!input.equals("Q")){
switch (input){
case "CS101":
//add course
break;
}
input = in.next();
}
You need to learn of Object Oriented Programming. This video Object-oriented Programming in 7 minutes gives an overview of some major concepts. Of course you need to learn them in depth. Anyways this is how I solved your problem. It doesn't exactly follow all you requirements because of lack of information i.e enroll method and Class Courses. This is just meant to show you what can you do.
// Create ArrayList
ArrayList<String> selectedCourses = new ArrayList<String>();
// Displays all courses available
System.out.println("The following courses available are:\n" + "1. COMPUTERSCIENCE101\n" + "2. CHEMISTRY101\n"
+ "3. ENGLISH101\n" + "4. HISTORY101\n" + "5. MATHEMATICS101\n");
// Creating scanner object
Scanner scanner = new Scanner(System.in);
// Prompting user. This is helpful otherwise the user would just keep staring at
// blank screen not knowing that program is asking for input.
System.out.print("Please enter how many courses you want to select: ");
int noOfCourses = scanner.nextInt();
scanner.nextLine();
// Looping the number of time user wants to select courses
for (int i = 0; i < noOfCourses; i++) {
// Prompting user
System.out.print("Please enter the course you want to select: ");
String course = scanner.nextLine(); // Instead of creating a new Scanner I am reusing the older one
selectedCourses.add(course); // Adding courses in arraylist
}
// Printing arraylist
System.out.println("\nCourses selected: " + selectedCourses.toString());
Output:
The following courses available are:
1. COMPUTERSCIENCE101
2. CHEMISTRY101
3. ENGLISH101
4. HISTORY101
5. MATHEMATICS101
Please enter how many courses you want to select: 3
Please enter the course you want to select: COMPUTERSCIENCE101
Please enter the course you want to select: CHEMISTRY101
Please enter the course you want to select: HISTORY101
Courses selected: [COMPUTERSCIENCE101, CHEMISTRY101, HISTORY101]

How to stop scanner from accepting input

I'm working on very simple code which asks you to enter how much money you have and and which products you wish to buy (on one line). The program is then supposed to tell you whether you have enough money to buy the products or not. Also, it should print the product with the lowest price.
Example:
Enter amount of money you have: 100
Enter products you want to buy and the value for each: Apple 10 and Orange 20
Output of the code:
you have enough money
the lowest price is (Apple 10)
I have 2 problems with this code
First, when I try to stop the scanner from taking inputs I'm supposed to enter "stop" as an input. However, in my case the action is only performed only if I enter "stop" 2 times. I don't know why.
I need to determine the minimum product value and print it. I have tried a lot of different things, but none of them worked for me.
This is my code so far:
Scanner input = new Scanner (System.in);
String productName="";
double totalPrice=0;
double productValue = 0;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (!(productName.equals("stop")) ){
if(input.hasNext()){ productName = input.next();}
if (input.hasNextDouble()){ productValue = input.nextDouble();}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
Your code is reading two items before checking to see if the user wants to stop and that is why you're having to provide two inputs. To determine the minimum value just keep track of the lowest value you've seen so far along with the name associated with that value.
Scanner input = new Scanner (System.in);
String productName="", minProductName = null;
double totalPrice=0;
double productValue = 0, minValue = -1;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (true){
productName = input.next();
if("stop".equals(productName))
break;
productValue = input.nextDouble();
if(minValue < 0 || minValue > productValue){
minValue = productValue;
minProductName = productName;
}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
System.out.println("Minimum product value: "+minProductName + " " +minValue);
input.close();
Input/Output:
How much money do you have?
100
please insert the items in the invoice (the name of product and its price): insert "stop" as the name of the product to finish your input
apple 10
orange 5
banana 50
stop
you have enough money
Minimum product value: orange 5.0
Considerations/Notes:
You may notice that this condition has been flipped:
if("stop".equals(productName))
This is intentional because if you have a null productName somehow then your code will throw a null pointer if you use productName.equals(...) but if you use a constant like "stop" there is no way this can be null so it will never throw a NullPointerException.
You never validate your input - what if the user enters something that is less than zero for the value? Is that valid? If not then what should happen?
Instead of parsing the user input the way you are now, try parsing the entire line at once and then splitting up the input string using String.split()
Also consider what the your first call to Scanner.nextDouble() is really doing. It will read the next double input by the user but will not read to the next line (won't read past the newline character)

Validating user input in java

Hi I am encountering a problem with a uni project I am working on. I am trying to validate the input so that the BookID that is entered when attempting to loan the book, is only valid if it exists in the array named 'BookList'. At the minute I have it working so that it validates it to make sure that an integer is entered, and not letters or negative numbers.
I have tried endlessly but I am stuck completely?? any tips or help, I would much appreciate it.
thanks
//loan a book method
public void loanBook() {
int loanID;
do {
System.out.println("Please enter the Book ID of the book that you wish to borrow");
while (!input.hasNextInt()) { // checking that the ID entered is an integer - validation
System.out.println("That is not an integer");
input.nextLine(); //pushing the scanner on
}
loanID = input.nextInt(); //setting the loanID variable equal to the input from the scanner.
}
while (loanID < 0 || loanID > 100000000); //VALIDATION - NEED TO CHANGE SO THAT WHILE LOAN ID EXISTS IN ARRAY LIST ????
for (int i = 0; i < BookList.size(); i++) { //for loop to go through and check for the ID entered to remove the book that it corresponds to
if (BookList.get(i).getBookID() == loanID ) {
System.out.println("The book named : " + BookList.get(i).getTitle() + " has now been taken out on loan. Please return within 2 weeks!");
BookList.get(i).setStatus("On Loan");;
}//end of if statement
}//end of for loop
} //end of return book method
You can use the .contains() method for Arraylists. You just need to make sure you are removing items depending on their status.
if(bookList.contains(loanID)){
//logic for book exists
}else{
//book is on loan.
}
Now as I said you need to make sure you are doing proper verification for removing of the books on loan etc for this to work. The way you have your logic right now is doing a LOT of unnecessary work with your loops. This way you can easily scan the list and find the item needed. Of course there are better ways to set up your lists etc but this should work keeping your code very similar.
EDIT
You requested information on how you would find the index of the item after you have verified it exists. This is still very simple. Once you have verified that the item exists you would use the line:
int index = bookList.indexOf(loanID);
This will return the index in your ArrayList for the location of the book. Once you have the index you can begin doing everything you were doing before with:
bookList.get(index).getBookId();
or
bookList.get(bookList.indexOf(itemId)).getBookId();
This is almost exactly what you were doing previously but cut down to 3 lines and can be made even shorter.
if (BookList.contains(loanID)) {
int index = BookList.indexOf(loanId);
if (!BookList.get(index).getStatus().equals("On Loan")) {
System.out.println("The book named: " + BookList.get(index).getTitle() + " has now been taken on loan.");
BookList.get(index).setStatus("On Loan.");
}else{
System.out.println("Book is on loan already.");
}
}else{
//logic for not existing.
}
Create a variable int isExist = 0; After getting the input from user...go through the array and see if that book exists. Then make isExist=1; And then of the loop just make if statement
if( isExist == 0) {
System.out.println("Book is not found");
}
By the way once you have found the book in the array you want to break out of the loop using break;

Unlimited number of user inputs

I have an assignment to make a program which allows the user to enter an unlimited
set of numbers until 0 is entered, to print the smallest and largest number, and to say if they are odd or even.
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Please note I only began learning Java last week and so am unfamilliar with the language
Many thanks!
I am comfortable with everything except on how to allow the user to enter as many numbers as desired and am unsure on how to start this. Should I be using loops or another method?
Since this is a homework, and you probably do not want us to do your homework for you. This is what you can do:
do{
//prompt user for input
//prompt user to continue (y/n)
//if 'n' was given
//proceed = false;
}while(proceed);
You can use a do-while or while loop. You can now prompt user for input infinitely till they decide to stop.
Update 1: (According to changes in question)
Terminating condition: when 0 is received as input:
do{
//prompt user for integer input
//if (input == 0)
//break; (exit loop)
//store input
}while(input != 0);
***Try to do it on your own.Use this for reference only.
I know its not right to give away the code as it is for your assignment.Just use (understand and learn)this if you didn't get the output.
int n=0,temp=0,z=0,i=0,j=0;
int []a=new int[1000]; //as size is not given by user assign the array with a much greater value
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Object for BufferedReader class used for reading elements
do{
System.out.print("Enter the number:");
a[n]=Integer.parseInt(br.readLine()); //String to integer conversion
n++;
System.out.println("Do you want to enter more numbers(0/1):");
z=Integer.parseInt(br.readLine());
}while(z!=0);
//Sorting
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
//Now after sorting the smallest number will be in the first location ie;
//"0" so inorder to check it is even or odd we take check its remainder when it is divided by 2.
if(a[0]%2==0){
System.out.println("The smallest number is : "+ a[0] + " & the number is even");}
else{
System.out.println("The smallest number is : "+ a[0] + " & the number is odd");}
if(a[n-1]%2==0){
System.out.println("The largest number is : "+ a[n-1] + " & the number is even");}
else{
System.out.println("The largest number is : "+ a[n-1] + " & the number is odd");}
A sample output is as follows :

How do I output this information that I have stored?

I have written this code so far, it is part of an assignment, but I am stuck and am not sure how to do part 2. I have completed part 1. Any suggestions on where to go from here?
Thanks!
Part 1.
Prompts the user for the following information and stores the input in appropriate variables:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
The user's age in months
The age in months of a sibling or friend of the user
The user's GPA
The displacement in liters of the user's car engine
Part 1. Code
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class InformationStationFinal{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String s1 = "yes";
String s2 = "no";
System.out.print("Are you left handed? Enter yes or no:");
String leftHand = input.next();
System.out.println("true");
System.out.print("Is your father at least 5ft 10 inches? Enter yes or no:");
String tall = input.next();
System.out.println("true ");
System.out.print("Enter your age in months: ");
int age = input.nextInt();
System.out.println(" ");
System.out.print("Enter the age of a sibling or friend in months: ");
int ageTwo = input.nextInt();
System.out.println(" ");
System.out.print("Enter your GPA as decimal, such as 3.58: ");
double gpa = input.nextDouble();
System.out.println(" ");
System.out.print("Enter displacement in liters of your cars engine:");
int liter = input.nextInt();
System.out.println(" ");
System.out.println("Are you left handed? " + " " + leftHand);
System.out.println("Is your father at least 5ft 10in? " + " " + tall);
System.out.println("Are you left handed or is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) || (tall.equals(s1))));
System.out.println("Are you left handed And is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) && (tall.equals(s1))));
System.out.println("Are your answers for left handed & father's height the same" + " " +
(leftHand.equals(tall)));
}
}
Part 2.
Prints out the following information, using either JOptionPane.showMessageDialog() or System.out.println() for the output:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
Whether at least one of the values from a and b are true (true if either or both are true)
Whether a and b are both true (false if at least one is false)
Whether the truth values of a and b are the same (true if both a and b are true or if both a and b are false)
Whether the user is older than his/her sibling/friend (as far as we can tell from the ages in months)
Whether the user's age in months is within 12 months of the age of his/her sibling or friend. You may want to use Math.abs() for this.
Whether the user's GPA is at least equal to the displacement of his/her car engine. For this item, use an else statement to print out some appropriate message if the condition is false.
Could someone please help me complete the second part of this question? Thank you.
Sounds like you have a bunch of conditions to check. The nice thing about booleans, they lend themselves well to "if" statements . . .
Look into:
if(someCondition)
{
// Do Something
}
else
{
// Do Something Else
}
At this point, you could use a single String to gather the results for later printing in a JOptionPane.showMessageDialog(). I won't code it all for you, but here's an example:
String result = "";
if(leftHand.equalsIgnoreCase("yes")) {
result += "You are left handed.\n";
} else {
// Other stuff
}
// ...
JOptionPane.showMessageDialog(null, result);
EDIT: If you're not interested in using JOptionPane, then you can use a single System.out.println() to print the entire string out as well. You just have to remember, when you're adding your answers to the String, you need a newline character.
For those questions you will need some conditional statements, i.e.:
if(leftHand.equals("yes")){
System.out.println("User is left-handed");
} else {
System.out.println("User is right-handed");
}

Categories