What is the best way to read user inputs via scanner? - java

I use some approaches similar to the following one in Java:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a= new int[3];
//assign inputs
for (int i=0;i<3;i++)
a[i] = scan.nextInt();
scan.close();
//print inputs
for(int j=0;j<3;j++)
System.out.println(a[j]);
}
However, generally the first input parameter is length and for this reason I use an extra counter (c) in order to distinguish the first element. When using this approach, the scanner does not read inputs one by one and checking the first and other elements in two blocks seems to be redundant.
// input format: size of 3 and these elements (4, 5, 6)
// 3
// 4 5 6
public static void getInput() {
int n = 0; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//block I: check the first element (size of array) and assign it
if (scan.nextInt() <= 0)
System.out.println("n value must be greater than 0");
else {
n = scan.nextInt();
array = new int[n];
}
System.out.println("Enter array elements:");
//block II: check the other elements adn assign them
while(scan.hasNextInt() && c<n) {
if (scan.nextInt() >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c] = scan.nextInt();
c++;
}
}
scan.close();
int sum = 0;
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
My question is "how can I modify this approach with a single block (while and for loop inside while)? I tried 5-6 different variations but none of them works properly?"

Hope this helps,
public static void getInput() {
int n; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//check the first element (size of array) and assign it
n = scan.nextInt();
while(n <= 0)
{
System.out.println("n value must be greater than 0");
System.out.println("Enter size:");
n = scan.nextInt();
}
array = new int[n];
System.out.println("Enter array elements:");
// check the other elements and assign them
while(c<n) {
int num = scan.nextInt();
if (num >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c++] = num;
}
}
scan.close();
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
Output:
Enter size:
-1
n value must be greater than 0
Enter size:
4
Enter array elements:
1
2
3
4
Sum = 10

I've optimized your code and fixed some bug.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
int n = scan.nextInt();
if (n <= 0) {
System.out.println("n value must be greater than 0");
return; // need to break from here
}
int c = 0;
int sum = 0; // no need for array
System.out.println("Enter array elements:");
// check the other elements and assign them
while (c++ < n) {
int next = scan.nextInt();
if (next >= 100) {
System.out.println("Array elements must be lower than 100");
c--; // ensure can reenter the number
} else {
sum += next;
}
}
scan.close();
System.out.println("Sum = " + sum);
}

Related

How to find the min and max values with number of occurances for each

I'm having trouble solving this homework problem. The problem wants me to create a program that reads user input of numbers and get the minimum and maximum values of those numbers.
Basically, the output should be as follows:
Enter number count: 10
Enter 10 numbers separated by space and press ENTER: 1 2 3 1 2 3 4 5 6 3
Min is 1 and has 2 occurrences
Max is 6 and has 1 occurrences
I was able to create methods to get the min and max. I don't know how to get the number of occurrences for the min and max with what I have. I also don't know how to get the scanner to read an input of integers on the same line.
import java.util.Scanner;
public class homework2
{
public int min(int[] array)
{
int min = array[0];
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public int max(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++)
{
myArray[i] = s.nextInt();
}
}
}
Here's a simple program to do what you need:
public static void main(String[] args) {
int[] array = {1, 2, 3, 1, 2, 3, 4, 5, 6, 3}; // get your actual array
int first = array[0];
// initial values
int min = first;
int minOccurs = 1;
int max = first;
int maxOccurs = 1;
for(int i = 1; i < array.length; i++) {
int current = array[i];
if(current == min) {
minOccurs++;
} else if (current < min) {
min = current;
minOccurs = 1;
}
if(current == max) {
maxOccurs++;
} else if (current > max) {
max = current;
maxOccurs = 1;
}
}
System.out.println("Min is " + min + " and has " + minOccurs + " occurrences");
System.out.println("Max is " + max + " and has " + maxOccurs + " occurrences");
// prints: "Min is 1 and has 2 occurrences"
// prints: "Max is 6 and has 1 occurrences"
}
One way is to store counts of each one of the numbers you see using a HashMap. The number itself can be the key and the value can be the count that you are incrementing.
You can also use a Math lib to output a min and max from the set of keys (numbers)
https://www.geeksforgeeks.org/java-math-min-method-examples/
https://www.geeksforgeeks.org/count-occurrences-elements-list-java/
Good luck!
Once you know what the maximum is, just count how many times that occurs in the array.
However, as #Babyburger points out, you don't need an array to compute either the maximum or how many times it occurs.
Here is one way to parse a line of space separated integer numbers into int array:
int[] array = Arrays
.stream(scanner.nextLine().trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
This should work for you. Let me know if you have questions:
import java.util.Scanner;
public class homework2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
System.out.println("Enter the elements of the array:");
int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = Integer.parseInt(s.next());
}
// take first element as max and min
int max = numbers[0];
int min = numbers[0];
// max and min exists so occurs at least once
int maxOcc = 1;
int minOcc = 1;
// start from i = 1; because we assigned the first element before
for (int i = 1; i < length; i++) {
int number = numbers[i];
if (number > max) {
max = number;
// start counting again
maxOcc = 1;
} else if (number == max) {
maxOcc++;
}
if (number < min) {
min = number;
// start counting again
minOcc = 1;
} else if (number == min) {
minOcc++;
}
}
System.out.println("max: " + max);
System.out.println("maxOcc: " + maxOcc);
System.out.println("min: " + min);
System.out.println("minOcc: " + minOcc);
}
}
Here is a solution to your problem. This takes a single string with numbers and spaces in-between, adds them to a dynamic array(ArrayList) and uses the min,max functions.
Do not initialize min and max=0 because we have to pick an integer from the provided list to start our comparison and that has to be the first element [0].
Code
import java.util.ArrayList;
import java.util.Scanner;
public class homework2 {
//Using static with functions because of the function calls in the Static
//main function
//Find the maximum number
public static int max(ArrayList<Integer> array) {
int max=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)>max)
max = array.get(i);
}
return max;
}
//Calculate Maximum number's occurences
public static int maxOccur(int max,ArrayList<Integer> array){
int maxOccur=0;
for(int i=0; i<array.size(); i++ )
if(max==array.get(i)) maxOccur++;
return maxOccur;
}
//Find the minimum number
public static int min(ArrayList<Integer> array) {
int min=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)<min)
min = array.get(i);
}
return min;
}
//Calculate Minimum number's occurences
public static int minOccur(int min,ArrayList<Integer> array){
int minOccur=0;
for(int i=0; i<array.size(); i++ )
if(min==array.get(i)) minOccur++;
return minOccur;
}
public static void main(String args[])
{
int minNum,maxNum;
Scanner in = new Scanner(System.in);
System.out.print("Enter the numbers separated by a space: ");
String number = in.nextLine();
//Separate the string by spaces in-between
String[] separatedNums = number.split(" ");
//Create a dynamic ArrayList to store any amount of integers
ArrayList<Integer> arrayList = new ArrayList<Integer>();
//Save the above string in the ArrayList after parsing into integer
for (String a : separatedNums)
arrayList.add(Integer.parseInt(a));
minNum=min(arrayList);
maxNum=max(arrayList);
//Output the results
System.out.println("Minimum Number="+minNum+" has
"+minOccur(minNum,arrayList)+" occurances");
System.out.println("Maximum Number="+maxNum+" has
"+maxOccur(maxNum,arrayList)+" occurances");
//Close the scanner
in.close();
}
}

Searching for a value in an array, and storing it if it doesn't exist

I am looking to input an integer between 10 and 100 into a one dimensional array, and if the value already exists anywhere in the array, do not insert it into the array, but notify user and resume input until 5 unique numbers are added.
Here is my code. I know it's not right, but you can see that what I am trying to do is use simple for loops and a search method to get the numbers, store them into the array and search for a duplicate. My problem in my code is that I can't seem to set the number I just entered as the variable 'key' which I need to send to the method 'search'.
// input an integer between 10 and 100, add to array and print results. if value is already in array, notify user, print array. keep adding to array until 5 unique values have been entered
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
list[i] = input.nextInt();
}
int count = search(list, key);
System.out.println("It has been entered.");
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].equals(key)) {
;
}
count++;
}
return (count);
}
}
Simple example with array. Could improve with alternate data structure list set.
The search() method is essentially included within the while() loop, namely the for() loop examples the search for a target number already being included.
int c = 0; is declared before the loops and makes sure to find 5 unique numbers.
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
boolean has = n >= 10 && n <= 100;
for (int i = 0; i <= c && !has; ++i)
if (list[i] == n)
has = true;
if (!has) {
System.out.println("It has been entered.");
list[c++] = n;
}
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
}
Alternate version:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Set<Integer> set = new HashSet<Integer>(5);
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
if ((n < 10) || (n > 100) || !set.add(n))
continue;
else {
System.out.println("It has been entered.");
c++;
}
}
System.out.println("Result = " + set);
s.close();
}
}
additionally, using search()
public class App {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter number: ");
int n = s.nextInt();
if ((n >= 10 && n <= 100) && search(list, n) == 0) {
list[i] = n;
System.out.println("It has been entered.");
} else
i--;
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == key) {
count++;
}
}
return count;
}
}
Edit: also added the 10-100 spec
edit2: using your approach with search() method
You are saving the input directly in the array.
Save the input in a temporal variable which you'll pass to search. And based on result of search you add to the array or prompt for another input.
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
int temp = input.nextInt();
if(search(list,temp) == 0)
list[i] = temp;
}else{
System.out.println("It has been entered.");
i--;
}
}

array while loop output Java

Ok, i got this working while loop that lets the user insert random numbers, if the number is 0 or if the loops length has been achieved then it will stop, now i have to output all the numbers that was inputed and the amount of the inputs (example 1, 2, 3 amount = 3). How do i output the array? i only get 0 from the println.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0 || a1[i] == a1.length){
break;
}else{
tal += a1[i];
}
}//End of while
System.out.println("The inserted numbers are are: " + a1[i]);
}//
First of all, store tal in array and increment i every time you store. Finally iterate through array to print elements entered
import java.util.Scanner;
public class Tset {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] a1 = new int[100];
int i = 0;
int tal;
while(true){
System.out.println("Insert number (0-end):");
tal = scan.nextInt();
if(tal == 0||i>=100){
break;
}else{
a1[i]=tal;
i++;
}
}//End of while
System.out.println("The inserted numbers are are: ");
for(int j=0;j<i;j++){
System.out.println(a1[j]+"\t");
}
System.out.println("amount is: " +i);
}//
}
Use an ArrayList instead of an array to collect the number input and then iterate over it to print them use its built-in lenght method to output the amount
I am not sure what you are trying to do, but this might help.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a1 = new int[100];
int i = 0;
int tal = 0;
int tmp;
do {
System.out.println("Insert number (0-end):");
tmp = scan.nextInt();
a1[i] = tmp;
tal += a1[i++];
} while (tmp != 0 && i < a1.length);
System.out.println("The inserted numbers are : ");
for (int j = 0; j < i-1; j++) {
if (j == i-2) {
System.out.print(a1[j] + ".");
} else {
System.out.print(a1[j] + ", ");
}
}
System.out.println("The sum is : " + tal);
}
Couple of issues:
You may want to put element you read into array like a1[i] = scan.nextInt(); and initializing tal as 0 and using a1[i] in if condition instead of tal.
You are not incrementing value of i and end's up overwriting the previous value.
Once you come out of loop, you just print 0th value of array which i think you entered 0 and came out of loop.
You can over come these as below:
Just after tal += a1[i]; increment value of i as:
i++;
Now to print your element, use a loop like:
System.out.print("The inserted numbers are are:");
for (int j=0; j<i; j++) {
System.out.print(" " + a1[j]);
}
System.out.println();

10 element Array will only accept 5 integers during Selection sort project

Ok, so this is for a Java class, but I'm not looking for someone to write the code, just help me debug this one. I want to enter 10 integers and have the inputs sorted in ascending order as they are entered then displayed, without any zeros (0) that may exist in the array.
Example of what the assignment should look like:
Enter 10 integers - one at a time...
Enter integer #1: 21
Sorted numbers: 21
Enter integer #2: 48
Sorted numbers: 21 48
Enter integer #3: 37
Sorted numbers: 21 37 48
etc....
I have tried a Selection Sort, Insertion and Bubble Sort, but the array will not hold or display more than 5 numbers.
Help.
Here is my Main:
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
int[] list = new int[10];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length; i++){
System.out.print("Enter integer #" + j + ": ");
list[i] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.length; p++){
if (list[p] !=0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
Here is my Selection Sort:
public class SelectionSort {
public static void sort (int[] list){
for(int i=0; i<list.length; i++)
{
for(int j=i+1; j<list.length; j++)
{
if(list[i] > list[j] )
{
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
}
}
Thanks in advance!
Why don't you use List insteed of array and ready-to-go sorting implementations from jdk -> Collections.sort() ?
Anyway the problem is that you are inserting new integers into already sorted array and that causes disfunction of your code. So as you inserting new elements on indexes 0,1,2,3,4 - sorting algorithm moves them to positions 5,6,7,8,9. From this point your inputs starts overriding sorted values with new ones from input - (Main loop i>=5).All in all, it accepted 10 integers, but 5 of them where kindly overriten.
Here is little modified version of your work whitch works like you want. Analyze it!
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
list[0] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
class SelectionSort {
public static void sort(int[] list) {
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] > list[j]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
i--;
break;
}
}
}
}
}
You are replacing sorted value with list[i] = input.nextInt(); with every input. So, 5 values always 0 in list. Use List<Integer> instead of int[] and add new value to List<Integer>. Try following code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
List<Integer> list = new ArrayList<>();
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < 10; i++){
System.out.print("Enter integer #" + j + ": ");
list.add(input.nextInt());
j++;
//SortMethod.sort(list, list.length);
// SelectionSort.sort(list);
Collections.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.size(); p++){
if (list.get(p) !=0)
System.out.print(list.get(p) + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
I just modified the lines below the comments I put (temp declaration and for loop).
This changes makes program support negative numbers too, read the comments below:
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
// Add temporal variable to store input
int temp = input.nextInt();
// Check for empty place in list (as far as it seems you don't care about zeros)
for (int p = 0; p < list.length; p++) {
if (list[p] == 0) {
list[p] = temp;
break;
}
}
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}

How can i generate all subsets of a variable length set?

I am trying to write a program that generates all the subsets of an entered set in java. I think i nearly have it working.
I have to use arrays (not data structures)
The entered array will never be greater than 20
Right now when i run my code this is what i get:
Please enter the size of A: 3
Please enter A: 1 2 3
Please enter the number N: 3
Subsets:
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 2 3 }
{ 2 3 }
{ 2 }
{ 1 2 }
this is the correct number of subsets (2^size) but as you can see it prints a few duplicates and not some of the subsets.
Any ideas where I am going wrong in my code?
import java.util.Scanner;
public class subSetGenerator
{
// Fill an array with 0's and 1's
public static int [] fillArray(int [] set, int size)
{
int[] answer;
answer = new int[20];
// Initialize all elements to 1
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int a = 0; a < set.length; a++)
if (set[a] > 0)
answer[a] = 0;
return answer;
} // end fill array
// Generate a mask
public static void maskMaker(int [] binarySet, int [] set, int n, int size)
{
int carry;
int count = 0;
boolean done = false;
if (binarySet[0] == 0)
carry = 0;
else
carry = 1;
int answer = (int) Math.pow(2, size);
for (int i = 0; i < answer - 1; i++)
{
if (count == answer - 1)
{
done = true;
break;
}
if (i == size)
i = 0;
if (binarySet[i] == 1 && carry == 1)
{
binarySet[i] = 0;
carry = 0;
count++;
} // end if
else
{
binarySet[i] = 1;
carry = 1;
count++;
//break;
} // end else
//print the set
System.out.print("{ ");
for (int k = 0; k < size; k++)
if (binarySet[k] == 1)
System.out.print(set[k] + " ");
System.out.println("}");
} // end for
} // maskMaker
public static void main (String args [])
{
Scanner scan = new Scanner(System.in);
int[] set;
set = new int[20];
int size = 0;
int n = 0;
// take input for A and B set
System.out.print("Please enter the size of A: ");
size = scan.nextInt();
if (size > 0)
{
System.out.print("Please enter A: ");
for (int i = 0; i < size; i++)
set[i] = scan.nextInt();
} // end if
System.out.print("Please enter the number N: ");
n = scan.nextInt();
//System.out.println("Subsets with sum " + n + ": ");
System.out.println("Subsets: ");
System.out.println("{ }");
maskMaker(fillArray(set, size), set, n, size);
} // end main
} // end class
The value of i always goes from 0 to N-1 and then back to 0. This is not useful to generate every binary mask you need only one time. If you think about it, you need to move i only when you have generate all possible masks up to i-1.
There is a much easier way to do this if you remember every number is already internally represented in binary in the computer and everytime you increment it Java is doing the adding and carrying by itself. Look for bitwise operators.

Categories