take input for array from user in java - java

I am working on a java code to get an array of integers from the user and then remove the integer in a selected index by the user. My code is already done but I don't know how to get array input from the user.
import java.util.*;
public class Test11 {
public static int[] removeTheElement(int[] arr, int index) {
if (arr == null || index < 0 || index >= arr.length) {
return arr;
}
int[] anotherArray = new int[arr.length - 1];
for (int i = 0, k = 0; i < arr.length; i++) {
if (i == index) {
continue;
}
anotherArray[k++] = arr[i];
}
return anotherArray;
}
public static void main(String[] args) {
Scanner adnan = new Scanner(System.in);
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println("Original Array: " + Arrays.toString(arr));
System.out.println("Index to be removed: ");
int index = adnan.nextInt();
arr = removeTheElement(arr, index);
System.out.println("New Array: " + Arrays.toString(arr));
}
}
Any help would be really appreciated.

I have modified your code in the main() to make it work for accepting arrays input from user.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of array: ");
final int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements to array: ");
for (int loop = 0; loop < size; loop++) {
array[loop] = scanner.nextInt();
}
System.out.println("Original Array: " + Arrays.toString(array));
System.out.println("Index to be removed: ");
int index = scanner.nextInt();
array = removeTheElement(array, index);
System.out.println("New Array: " + Arrays.toString(array));
}

You can read the array as a string like : 1 2 3 4 ..., and then extract and cast the values. Or you can ask the user for the size of the array (number of elements that the user wants to insert ) and then loop to scan and save each element.
The first case :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] stringArray = scanner.nextLine().split(" ");
int[] parsedValues = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
parsedValues[i] = Integer.parseInt(stringArray[i]);
}
System.out.println(Arrays.toString(parsedValues));
}
The second case :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] parsedValues = new int[size];
for (int i = 0; i < size && scanner.hasNextInt(); i++) {
parsedValues[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(parsedValues));
}

Related

Need to print a string array

My task is to read the strings by input, and then display the strings that have more than 4 vowels in each. I have this code:
import java.util.Scanner;
public class Main {
static boolean vowelChecker(char a) {
a = Character.toLowerCase(a);
return (a=='a' || a=='e' || a=='i' || a=='o' || a=='u' || a=='y');
}
static int counter(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++)
if (vowelChecker(str.charAt(i))) {
++count;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
String str = scanner.nextLine();
int b = counter(str);
if (b > 4) {
System.out.println("What do I write here?");
}
}
}
And my question is: how to correctly write the code so that the output would be strings from input that have more than 4 vowels?
import java.util.Scanner;
public class Test {
private static final char[] VOWELS = new char[]{'a', 'e', 'i', 'o', 'u', 'y'};
public static void main(String[] args) {
// Initialize and open a new Scanner
final Scanner scanner = new Scanner(System.in);
// Get the number of lines we want to analyze
System.out.print("Enter the number of elements you want to store: ");
final int n = Integer.parseInt(scanner.nextLine());
// Get all the lines from the user
System.out.println("Enter the elements of the array: ");
final String[] lines = new String[n];
for(int i = 0; i < n; i++) {
lines[i]=scanner.nextLine();
}
// Close the Scanner
scanner.close();
// Check each line, count the number of vowels, and print the line if it has more than 4 vowels.
System.out.println("\nInputs that have more than 4 vowels");
for(int i = 0; i < n; i++) {
if (countVowels(lines[i]) > 4) {
System.out.println(lines[i]);
}
}
}
private static boolean isVowel(char a) {
for (int i = 0; i < VOWELS.length; i++) {
if (Character.toLowerCase(a) == VOWELS[i]) {
return true;
}
}
return false;
}
private static int countVowels(final String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
count++;
}
}
return count;
}
}
Like others have pointed out, you never read from the array.
Read for each of the strings, if the counter() returns a value larger than 4, we want to print it. So, this could do the trick:
for(int i=0; i<n; i++)
{
if (counter(array[i]) > 4)
System.out.println(array[i]);
}
Using nextInt won't absorb the newline character \n, that's why you are inputting 1 string less. There are some workarounds that you can read about here.
So this first part makes sense :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store:
");
int n;
n=scanner.nextInt();
String[] array = new String[100];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=scanner.nextLine();
}
after this part I would just do :
for (String s: array) {
if (Objects.isNull(s))
break;
if (count(s) >= 5) {
System.out.println(s);
}
}
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
class Main {
static long counter(String str) {
return Arrays.stream(str.split(""))
.filter(c -> Arrays.asList("a", "e", "i", "o", "u", "y").contains(c.toLowerCase()))
.count();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
int n;
n = scanner.nextInt();
scanner.nextLine();
String[] array = new String[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
String str = scanner.nextLine();
if (counter(str) > 4) {
array[i] = str;
}
}
System.out.println(Arrays.toString(Arrays.stream(array).filter(Objects::nonNull).toArray(String[]::new)));
}
}

I want to convert Vararg Integer to Vararg int?

The below code is working fine using Integer values for my variadic method. But I want to use "int" instead of "Integer".
Here is the code:
package JavaPracticeShuffler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(Integer...a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(Integer...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}
I want to use "int....variable" instead of "Integer...variable" on my methods. I am assuming that I need to convert variable "intarray" to an int.
Please help I'm stuck on that part, thanks.
You can create a int array from your List by utilizing a for loop with autoboxing. Then you can change all the method signatures.
int[] intarray = new int[lnumber.size()];
for(int i = 0; i < intarray.length; i++)
intarray[i] = lnumber.get(i);
You can also use Streams.
int[] intarray = lnumber.stream().mapToInt(Integer::intValue).toArray();
You need to do the below steps to changes your program to from Integer to int...
Change parameter of DisplayNumbers(Integer...a) to DisplayNumbers(int...a)
Again change parameter of SumOfNumbers(Integer...a) to SumOfNumbers(int...a)
After that, you need to do some code changes in the main method. i.e. instead of
Integer[] intarray = new Integer[lnumber.size()];
intarray = lnumber.toArray(intarray);
you need to write
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
Please find the complete program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MediumLevelExcercisesA {
Scanner number;
Scanner yorn;
public MediumLevelExcercisesA(){
}
static void DisplayNumbers(int[] a) {
for (int b = 0; b < a.length; b++) {
System.out.print(a[b]);
System.out.print(" ");
}
}
static void SumOfNumbers(int...a) {
int total = 0;
for (int b = 0; b < a.length; b++) {
total += a[b];
}
System.out.println(" ");
System.out.println("Sum: " + total);
}
public static void main(String[] args) {
MediumLevelExcercisesA obj01 = new MediumLevelExcercisesA();
List<Integer> lnumber = new ArrayList<Integer>();
boolean numbercounter = true;
while (numbercounter) {
obj01.number = new Scanner(System.in);
System.out.println("Please input a number");
int inputnumber = obj01.number.nextInt();
lnumber.add(inputnumber);
System.out.println("Number/s you've entered so far are the following: " + lnumber);
obj01.yorn = new Scanner(System.in);
System.out.println("Do you want to continue?");
String iyorn = obj01.yorn.nextLine().toUpperCase();
if (iyorn.equals("YES")||iyorn.equals("Y")) {
System.out.println("You've answered yes, program will proceed.");
}
else if (iyorn.equals("NO")||iyorn.equals("N")) {
System.out.println("You've answered no, program ends.");
numbercounter = false;
break;
}
else {
System.out.println("Answer not understood, program continues.");
}
} //end of while loop.
System.out.println("Final review of numbers entered: " + lnumber);
//Remove below two commented line because it is not need further
//Integer[] intarray = new Integer[lnumber.size()];
//intarray = lnumber.toArray(intarray);
// This can be used for if not java 8 compatible
/*int[] intarray = new int[lnumber.size()];
Integer[] temp = lnumber.toArray(new Integer[lnumber.size()]);
for (int n = 0; n < lnumber.size(); ++n) {
intarray[n] = temp[n];
}*/
//Java 8 and above
int[] intarray = lnumber.stream().mapToInt(i -> i).toArray();
MediumLevelExcercisesA.DisplayNumbers(intarray);
MediumLevelExcercisesA.SumOfNumbers(intarray);
}
}

How to declare an array with specific indexs only once in Java?

I am using methods to create a choose your own adventure story. One of the methods is the following:
public static void storeChoices(){
Scanner sc = new Scanner(System.in);
String arr [] = new String[6];
if(arr[0] == null){
arr[0] = "Gucci";
arr[1] = "Tesla";
arr[2] = "Canada Goose";
arr[3] = "Rolex";
arr[4] = "Saks Fifth Avenue";
arr[5] = "Nike";
}
for(int i = 0; i < arr.length; i++){
System.out.println(" " + (i+1) + ")" + arr[i]);
}
System.out.println("Pick a number as your choice: ");
int choice = sc.nextInt();
sc.nextLine();
for(int x = 0; x < arr.length; x++){
arr[choice] = "Dr. Java has already visited this store";
}
}
I want to declare the array at the beginning only once because it changes depending on the choice the user picked. Every time I call the method again, declaring the array causes any changes I made to reset. How do I declare that array only once so that when I call the method, the changes I make don't reset? I just learned a little bit of methods so I am pretty new to this.
If you are not using threading mechanism then declare it as a static variable to the class
public class TestClass1 {
static String arr [] = new String[6];
public static void storeChoices(){
Scanner sc = new Scanner(System.in);
if(arr[0] == null){
arr[0] = "Gucci";
arr[1] = "Tesla";
arr[2] = "Canada Goose";
arr[3] = "Rolex";
arr[4] = "Saks Fifth Avenue";
arr[5] = "Nike";
}
for(int i = 0; i < arr.length; i++){
System.out.println(" " + (i+1) + ")" + arr[i]);
}
System.out.println("Pick a number as your choice: ");
int choice = sc.nextInt();
sc.nextLine();
for(int x = 0; x < arr.length; x++){
arr[choice] = "Dr. Java has already visited this store";
}
}
}
In a very simplistic case, just define it as a field, and then check if null
public class Main {
String [] arr = null;
public static void main(final String[] args) {
new Main().myMethod ();
}
private void myMethod () {
if (arr == null) {
arr = new String [] {"Gucci" , "Tesla", "Canada Goose"};
}
}
}

How can I get all the permutations from a scanner input to array?

I am trying to find all permutations of a pin number coming from a scanner. I have got this bit so far which I guess sets an array with custom digits. How can I get this code to show me all the possible options? Bare in mind that I am new to Java so simple explanations would be the best. Thanks
import java.util.Arrays;
import java.util.Scanner;
public class Methods {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter first digit: ");
arr[0] = sc.nextInt();
System.out.println("Please enter second digit: ");
arr[1] = sc.nextInt();
System.out.println("Please enter third digit: ");
arr[2] = sc.nextInt();
System.out.println("Please enter fourth digit: ");
arr[3] = sc.nextInt();
System.out.println(Arrays.toString(arr));
}
}
Hey you can use the following code to create an array of n length and calculate the permutations:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("please enter the length of you array: "); // 4 if you want a 4 digit pincode
int length = sc.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
System.out.printf("Please enter a value for digit #%s: ", i);
arr[i] = sc.nextInt();
}
StringBuilder bldr = new StringBuilder();
Arrays.stream(arr).forEach(bldr::append);
permutation(bldr.toString());
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
Also check this question for more info about permutations.

Trying to print the frequency of integers in an array

I'm trying to print out the frequency of each integer in an array
import java.util.*;
public class NumFrequency {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers your going to input, up to 50");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the "+ num + " numbers now.");
for (int i=0 ; i<array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("array created");
printArray(array);
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
private static int[] intFreqArray = new int[51];
public static void FreqOfInt(int[] array, int num) {
for (int eachInt : array) {
intFreqArray[eachInt]++;
}
for (int m = 0; m<intFreqArray.length; m++) {
if (intFreqArray[m] > 1) {
System.out.println(m+ " occurs " + intFreqArray[m] + " times.");
}
}
}
}
It'll print out the array created by the user but nothing after that I'm lost as to why it wont print out the last part.
You need to call FreqOfInt before you print.
Note that we normally use lower case letters for the names of Java methods.
In main, the last method call is to printArray, but you never call FreqOfInt. That's why that output doesn't show up.
Call it after calling printArray.

Categories