Java: using loops with no pre-defined stopping condition - java

I have to write a program which keeps track of items scanned by 2 employees in a bar-code reader. It should
Allow input of the codes for the different items.
Display an error message each time an employee is scanning an item which he has already scanned.
Display the total number of items scanned by each employee.
Display the total number of different items present in the warehouse.
Basically, since I have not been told how many items are present I am wondering if I should use a loop for this or not? If yes, which loop should I use?
I do not want the code for the whole program. I just want to know if I need to use a loop and which one..
I used a for loop at first until I realized that it was wrong to assume the number of items present. I did only the first 2 parts:
public class MyClass1{
public static void main(String[] args) {
Set<Integer> h= new HashSet<Integer>();
Scanner input= new Scanner(System.in);
System.out.println("Employee 1:");
for(int i=0;i<5;i++){
boolean s= h.add(input.nextInt());
if(!s){
System.out.println("Item already exist!");
}
}
System.out.println("Employee 2:");
for(int x=0;x<5;x++){
boolean sh= h.add(input.nextInt());
if(!sh){
System.out.println("Item already exist!");
}
}
}
}

For this I would suggest you use a while loop.
// This loop will loop until the if statement's condition evaluates to true.
while(true){
// Code for processing the input et.c
if(someCondition) break; // The "break" keyword exits the last entered loop
// Code for processing the input et.c
}

Related

Adding user input in Arraylist

I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}

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.")
}
}

Creating an ArrayList Grocery List And Displaying Results in a table

I have been working on this assignment for weeks and need some assistance. Please don't refer me to JavaDocs as I have reviewed them countless times and have been unable to find the solution to my program.
This is what I need to do:
Add items to the ArrayList, one at a time, based on user typed input. The user will be prompted for the String to be stored in the ArrayList and then hit enter. The user will be able to continue to add items to the ArrayList until they just hit enter without typing anything.
Once the user does this (hits enter without typing anything), the program will display all of the elements of the ArrayList, both the index and String values, in a table. It will do this via a single loop
This is the code that I have so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.ArrayList;
// declares a name for the class
public class GroceryList2 {
/**
* Allows the program to be run and throws the Input-Output exception
* error
*/
public static void main(String[] args) throws IOException {
BufferedReader userInput =
new BufferedReader( new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);//allows for input
// declares the ArrayList to be a String
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Milk");
myArr.add("Cheese");
myArr.add("Eggs");
myArr.add("Bread"); //the values of the ArrayList already entereed
// the loop that allows the criteria to run
while(true) {
if(myArr.isEmpty()== false ) {
System.out.println("Enter the items for the grocery list: ");
String item = in.next();//asks and allows for input
myArr.add(item);
}
else if(myArr.isEmpty()== true ) {
for (int i=0; i<myArr.size(); i++ ) {
// displays the list after the input
System.out.print(
"The Grocery List "+ i+ ": "+ myArr.get(i));
}
}
}
}
}
The code compiles, but when I just press enter, it doesn't display the grocery list, it waits for another entry.
change the conditions in the if stattements, just swap them round. O rbetter improve by doing
if(myArr.isEmpty())
and then int he second
if(!myArr.isEmpty())
#Cece Inside the while loop you're not actually doing what you should in order to serve your purpose.
First of all, at every iteration the conditional myArr.isEmpty()== false will be validated (because your myArr array is never empty, as you already populate it before entering the while loop), so the execution of the code will go always to the same conditional branch. Just as a side note, you could write this more elegantly like this: !myArr.isEmpty.
Second, you're reading strings from the user, but all you do is add them to the array. As the else branch is never reached, the content of the array is never dumped. Just as a side note, the if statement after the else statement is redundant. You can safely remove it.
Third, the issue with your code is that you're never checking if the user input is empty. Instead, what you check is whether the groceries array is empty or not.
This is how I'd write the while loop:
while(true){
String item = in.next();
if(item.isEmpty()){
System.out.println("The Grocery List: ");
for(int i=0; i<myArr.size(); i++) {
System.out.println(i + ": "+ myArr.get(i));
}
break;
}
else{
myArr.add(item);
}
}
Let me know if you don't understand any part of my code.

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Retrieves and display endless amount of numbers in an array

I"m trying to make a program that retrieves an endless amount of numbers that user inputs until the user quits and display the numbers .Here is the code I have so far.After entering the first and second number it shows an exception at the line array1[i]=s1
import java.util.Scanner;
public class Program_2 {
public static void main(String[] args) {
int a=1,i;
Scanner sn = new Scanner(System.in);
String[] array1= new String[a];
for(i=0;i<a;i++)
{
System.out.println("Enter Value Number "+ (i+1));
System.out.println("Press Q or q to Exit");
String s1=sn.next();
if(s1.equalsIgnoreCase("q"))
{
for(i=0;i<a;i++)
{
System.out.println("Value of Number "+(i+1)+" is "+ array1[i]);
}
a=0;
}
else
{
array1[i]=s1;
a=(i+2);
}
}
}
}
Your array is of size 1 (a is 1 at the beginning of your code).
The first input works because i is 0 and array1[0] exists. The second input crashes because array1[1] does not exist.
You need to increase your array. That can be done by copying the array into a larger one and using the result of the copy, but that is clumsy.
Better way to do it is to use an ArrayList instead of a simple array and you do not have to worry about the size as it is managed automatically.
For one, a is only incremented when they press q, when you go to the else statement. So the the for loop is going to end after a couple of iterations.
You also set a to 0 in the inside for loop, making sure it won't run more.
Also, your quit code doesn't quit.

Categories