Retrieves and display endless amount of numbers in an array - java

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.

Related

"If" Statement Will Not Print in Loop

My code works, there's is just one problem. The code is meant to be about printing the numbers in between two user inputs. That part of the code works, however if the first number is greater than the second number it is meant to not print and ask again. Everything up to that point works, however if the first number is greater than the second, the console and code just end, and I cannot figure out why? Can you guys help and explain what I am doing wrong? Thanks! Here is my code:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
while (higherNum>=lowerNum){
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. "); // this does not print
}
}
System.out.println(lowerNum++);
}
Your loop only starts if higherNum >= lowerNum, which means your if condition inside the loop will never be true.
To achieve your output, you should do something as following.
while (lowerNum>higherNum ){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. "); // this does not print
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
}
while(lowerNum <= higherNum) {
System.out.println(lowerNum++);
}
I would suggest that you use your if condition first:
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
} else{
while (higherNum>=lowerNum){
System.out.println(lowerNum++);
}
}
It's happening because if the lowerNum is bigger than the higherNum your while condition would result in false and won't print anything since the error message is inside the while loop.
Your if should be before while. I fixed some other things on the way.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum = 0, lowerNum = 1;
while(lowerNum>=higherNum){
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
if(lowerNum>=higherNum){
System.out.println("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
} else {
while(lowerNum<higherNum-1){
System.out.println(++lowerNum);
}
}
}
}
You can give the number inputs with a method for restarting the process. Recursive option would be helpful for that issue.
public void TakeNumbers(){
Scanner reader = new Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
TakeNumbers();
System.out.println(lowerNum++);
}
public static void main(String[] args) {
TakeNumbers();
}

Java: using loops with no pre-defined stopping condition

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
}

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need

Get user to input integers

I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

Categories