String array out of bounds [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to make an array of type string of which the size and strings are inputted by the user and i keep getting error ArrayIndexOutOfBoundsException There is similar threads i found pertaining to this but none of which have solved this error. in my for statement if i take out the equal to and just do less than i receive no errors but i can only input one name less than the number i input. If i leave the code as is everything appears to work as it should minus the error. I understand i am getting this fault because my array is going out of bounds but i cant figure out why. please help! thank you!
package sales;
import compare.*;
import java.util.*;
public class Sales {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter number of employees to compare:");
int numEmp = scan.nextInt();
while(numEmp < 2){
System.out.println("Has to be at least 2 employees:");
numEmp = scan.nextInt();
}
String[] names = new String[numEmp];
System.out.println("Enter employees name:");
for(int i=0;i<=names.length;i++){
names[i]=scan.nextLine();
}
}
}

Change the condition of the for to i<names.length instead of i<=names.length.
scan.nextLine(); //add this
for(int i=0;i<names.length;i++){
names[i]=scan.nextLine();
}

Related

How to store Strings in Array of string through user input and print all of them? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
how to determine if a String starts with a specific character?
(2 answers)
Closed last month.
I've given this task:
Ask user to enter 5 City name.
Only 1 output outside loop "Please enter city name"
Then Story each city into the array
then using for loop find the cities start with Letter "D"
Print the Cities name only in output.
NOTE: Do not append anything to output text. Test will fail if you append text. NOTE: Do not include "Please enter city name" inside first loop. (Test will fail)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] cityname = new String [5];
System.out.println("Please enter city name");
sc.next();
for(int i = 0; i < cityname.length; i++){
cityname[i] += sc.next();
}
System.out.println(cityname[]);
}
}
I wrote this and don't know what to do next :(

Can someone tell me why am I getting java.lang.ArrayIndexOutOfBoundsException error in my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am working on a Java program to iterate through two arrays and compare the first one to the second for any matches. It should return all the numbers/strings that DON'T MATCH as an array list. I am done, but I am not sure why I am getting an ArrayIndexOutOfBoundsException error. This is my code:
package test;
import java.awt.List;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayComparer {
public static ArrayList<String> ArrayComparer(String[] arrayOne, String[] arrayTwo){
// if one is bigger than start by comparing the smaller one to the bigger one
// as if it were the other way the bigger one would run out over numbers to compare
// declaring the array for holding all the non-matching telephone numbers to be returned
ArrayList<String> nonMatchingTelephoneNumbers = new ArrayList<String>();
for(int i = 0; i<arrayOne.length; i++){
int strikes = 0;
// for each value of the first one it should go through all the values of the second and compare each
for(int i2 = 0; i<arrayTwo.length; i2++){
if(arrayOne[i] != arrayTwo[i2]){
strikes++;
if(strikes == arrayTwo.length){
// meaning it has gone through ALL of arrayTwo and couldn't find a match
nonMatchingTelephoneNumbers.add(arrayOne[i]);
}
}
}
}
return nonMatchingTelephoneNumbers;
}
public static void main(String[] args) throws IOException {
// declaring the first list of telephone number
String[] ArrayListOne;
// declaring the second list of telephone numbers
String[] ArrayListTwo;
// splitting up the user input of telephone numbers by commas
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your first array of telephone numbers, split by commas");
ArrayListOne = myObj.nextLine().split(","); // Read user input
// once it has iterated through all of the telephone numbers in the first list, ask for the second list
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your second array of telephone numbers, split by commas");
ArrayListTwo = myObj2.nextLine().split(","); // Read the second user input
// once it has collected and sorted all the user input, the ArrayCOmparer method should be called
// to compare them and return the telephone numbers that DON'T MATCH
ArrayComparer(ArrayListOne, ArrayListTwo);
}
}
The error is on line 22, where it says if(arrayOne[i] != arrayTwo[i2]){.It also doesn't say there is an error on line 22 until I run it. Can someone please tell me why I am getting this:console error?
Hi i think this is causing the error
for(int i2 = 0; i<arrayTwo.length; i2++){
You should replace it with:
for(int i2 = 0; i2<arrayTwo.length; i2++){

char digit to integer conversion [duplicate]

This question already has answers here:
Using charAt method, won't add them as an Int, and wont print as string. Will explain better
(4 answers)
Using charAt in System.out.println displays integer?
(5 answers)
Why does this code print the ASCII value instead of the character
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an ArrayList. I'm sure someone can help me out fairly quickly
My problem is as follows. When I print out all the values in the ArrayList, It is printing out much higher numbers e.g. 1234 = 49 50 51 52.
I think what is happening is that it is printing out the ASCII values rather than the numbers themselves. Can anyone spot where and why this is happening?
I have tried changing the int variable barcodeNumberAtI to a char, which yields the same result.
Apologies for lack of comments but this was only supposed to be a quick program
int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();
public void addNumbers(){
Scanner s = new Scanner(System.in);
do{
System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();
for(int i = 0; i < barCode.length(); i++){
barcodeNumberAtI = barCode.charAt(i);
System.out.println(barcodeNumberAtI);
numbers.add(barcodeNumberAtI);
}
System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));
}
public void displayNumbers(){
for(int i = 0; i < numbers.size(); i++){
System.out.print(numbers.get(i));
}
}
Happens at this line: barcodeNumberAtI = barCode.charAt(i);
barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.
Use this instead:
barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);
What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument.
Here's a link to the documentation

Java: How do I get a Scanner object to ignore unwanted/invalid inputs? [duplicate]

This question already has answers here:
Scanner input validation in while loop
(3 answers)
Closed 5 years ago.
I am trying to set up a simple text tree that reads in either single-characters (y/n) or integers that correspond to a printed list (1-4). I want to know the easiest way to have the program ignore user inputs that don't correspond to the given options like so:
import java.util.Scanner;
public class simpleMenu
{
Scanner sc = new Scanner(System.in);
String choicePick;
public static void main(String[] args)
{
System.out.println("Would you like to continue? (y/n)");
choicePick = sc.next();
if(choicePick.equals("y"))
{
// The program continues.
}
else if(choicePick.equals("n"))
{
// The program closes.
}
else
{
/*
The scanner ignores the input, ideally without having to restate the question.
The program does not quit or move on until "y" or "n" is entered.
*/
}
}
}
Bonus points if you can help me implement a 'back' option that takes me to the previous choice.
While the next string is not Y or N sc.next() until it is. Then use that string.

Java while loop working with user inputs [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 5 years ago.
I'm learning Java and trying to make a small program.
I made a list and a while loop. Everytime the user inputs something it should save the input to the list. Only if the input is "0" then i want it to break the while loop and print out everything whats inside the list. So it has to keep asking the user for an input till he insert 0. At the moment i don't have a teacher. I'm doing this all on my own. Don't blame me for my bad writting skills...
import java.util.ArrayList;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
while (true) {
ArrayList nummer = new ArrayList(); // make new list
Scanner input = new Scanner(System.in); // start scanner
System.out.print("Voer uw naam in: ");
String naam = input.nextLine(); // scanner waiting for input + enter
if (naam == "0") {
System.out.println("Wrong, exit!");
input.close();
for (Object item : nummer) { // foreach-loop
System.out.print(item);
}
break;
} else {
nummer.add(naam);
continue;
}
}
}
}
Could someone take a look to it and tell me what's wrong with it?
Thanks!

Categories

Resources