How to declare an array with specific indexs only once in Java? - 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"};
}
}
}

Related

take input for array from user in 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));
}

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

How do I store the user input that is indented by a space into the String array and convert the number into int array?

I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class

Run Time Error_String index out of bound Exception_Printing string odd and even indexes

Code :
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sa = new String[n];
for(int i=0;i<n;i++){
sa[i] = sc.nextLine();
}
String odd="";
String even="";
for(int i=0;i<n;i++)
{
for(int j=0;j<sa[i].length();j++)
{
if(j%2!=0){
odd = odd+sa[j].charAt(j);
}
else {
even = even+sa[j].charAt(j);
}
}
System.out.println(odd+" "+even);
}
}
}
ISsue : GEtting run time exception while running the code. --> String index out of bound exception
You can try below code. It is because of calling a method like nextInt() before sc.nextLine()
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.
You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array size");
int n = Integer.parseInt(sc.nextLine());
String[] sa = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element "+i);
String val = sc.nextLine();
sa[i]=val;
}
String odd = "";
String even = "";
for (int i = 0; i < n; i++) {
for (int j = 0; j < sa[i].length(); j++) {
if (j % 2 != 0) {
odd = odd + sa[j].charAt(j);
} else {
even = even + sa[j].charAt(j);
}
}
System.out.println(odd + " " + even);
}
}

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);
}
}

Categories