Simple for loop issue with arrays - java

This is the code I have right now
for (int i = 0; i <= listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i + 1) + ": ");
listOfPeople[i] = name;
}
List of people is a properly declared list of Strings with the length of a value the user sends in. The error that is happening is that when I run the program, I get this:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
Jordan
Person 4:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at RGG.main(RGG.java:20)
I am not quite sure what is wrong, but I have tried removing the = in the for loop declaration, then I get this output:
Person 1:
Jordan
Person 2:
Jordan
Person 3:
After the third prompt, the code moves on and I cant type in anything there.
Does anyone know what might be happening? Thanks in advance!

Remove the = in this expression i <= listOfPeople.length;. Its causing you to access an element of the array that does not exist.
for (int i = 0; i < listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
Full Example:
public class PersonArrayTest {
public static void main(String[] args) {
String[] listOfPeople = new String[5];
assign(listOfPeople);
System.out.println(Arrays.toString(listOfPeople));
}
public static void assign(String[] listOfPeople) {
Scanner scnr = new Scanner(System.in);
for (int i = 0; i < listOfPeople.length; i++) {
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
}
}

With this line
for (int i = 0; i <= listOfPeople.length; i++){
You are advancing one beyond the end of the array, length 3, which has valid indices 0-2. 3 is an invalid index.
When you remove the =, you get the corrected version:
for (int i = 0; i < listOfPeople.length; i++){
which stops after the 2 iteration, which is the end of the array, before you run off the end of the array.

change this the <= sign in forloop
for (int i = 0; i < listOfPeople.length; i++)

I am make an educated guess that you are using Scanner#nextInt to get the input for the length of the array. Something along the lines of this:
String[] listOfPeople = new String[scnr.nextInt()];
I've garnered this because your loop code looks like this:
take input for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
But your output shows this:
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
So what actually must be happening is this:
silently advance past whatever scnr is still retaining for i == 0
print prompt #1
take input for i == 1
print prompt #2
take input for i == 2
print prompt #3
nextInt orphans a new line character. (So will any calls to next_ besides nextLine.) That's why your first input is skipped. Calling scnr.nextLine in the first iteration of the loop just advances the Scanner past the last line.
Change the loop to this:
// skip the last new line
scnr.nextLine();
// < not <=
for (int i = 0; i < listOfPeople.length; i++) {
// prompt before input
System.out.println("Person " + (i + 1) + ": ");
// you don't need that extra String
listOfPeople[i] = scnr.nextLine();
}

Related

Split long sting in new lines and check each line first word in java

I have a string that I split based on delimiter on new lines. I'm wondering now how to check the first word index[0] what word is but can't find a way to actually go trough the elements and check.
May be my approach is totally wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
int ask = 0;
for (int i = 0; i < stringArr.length; i++) {
if (stringArr[0].equals("radio")) {
ask = 10;
} else if (Objects.equals(stringArr[0], "tv")) {
ask = 15;
} else {
System.out.println("Invalid media.");
}
}
System.out.println(ask);
}
Then when I input radio 3 7210>>tv 4 2345>>radio 9 31000>>
The output should be:
10
15
10
Instead - got nothing. Empty line and the program ends.
Is something like this what you want:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
for (int i = 0; i < stringArr.length; i++) {
int ask = 0;
String[] words = stringArr[i].split(" ");
if (words[0].equals("radio")) {
ask = 10;
System.out.println(ask);
} else if (words[0].equals("tv")) {
ask = 15;
System.out.println(ask);
} else {
System.out.println("Invalid media.");
}
}
Input:
radio 3 7210>>tv 4 2345>>radio 9 31000>>
Output:
10
15
10
First of all, I defined the scanner, not sure if you did that but pretty sure you did.
The elements of stringArr will include the random numbers between each ">>". That means, in each element, we should create a new list split by " " to isolate the "radio" and "tv" as the first element.
Additionally, I just rewrote the else-if statement that checks if the first word of the phrases separated by ">>" is "tv" by using the .equals() method as your original if statement did.
Finally, since you are printing out a number EACH time the code encounters a ">>", we should print out ask inside of the for loop.
EDIT:
Moved the System.out.println(ask) inside of the if and else-if statements so it will only run with valid media.
Other than that your code worked perfectly :> , let me know if you have any further questions or clarifications!

How to print the selected name in the array?

How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}

How to make for loop stop when scanner is at the very end of the input

I'm currently trying to make a program that will allow the user to enter any amount of integers (I'm only asking them to enter 9 for now as a test) and have the rotateArray function rotate the array of integers. For example:
input: 1 2 3 4 5
output: 5 4 3 2 1
The reason as to why I included the arraylist is because I want to make the program dynamically allocate memory so that the user can enter as many single digit inputs as well. My problem is with a for loop I'm currently using. I"m looking for a way to properly make it so that the for loop stops when it hits the very end of the user's input. I tried using scan.nextInt().isEmpty() but that did not work as intended.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("This program takes two arrays, compares them, and "
+ "determines whether the original array has been rotated and put "
+ "into another array. \nWatch what happens when the original "
+ "array = [0,1,2,3,4,5,6,7,8,9] is compared to an array with contents: \n"
+ "[9,7,5,3,1,8,6,4,2,0]");
int[] original = {0,1,2,3,4,5,6,7,8,9};
int[] notRotated = {9,7,5,3,1,8,6,4,2,0};
int[] rotatedArray = {9,8,7,6,5,4,3,2,1,0};
boolean rotation;
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
System.out.println("\n Watch what happens when the original array is compared to an array"
+ " with contents \n [9,8,7,6,5,4,3,2,1,0]");
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
ArrayList<Integer> userArray = new ArrayList<Integer>(9);
System.out.println("This program can also rotate arrays that contain "
+ "single digit integers.\n Enter 9 single digit "
+ "integers separated by spaces");
//*****************************************************
userArray.add(scan.nextInt());
for(int i = 0; i<userArray.size(); i++)
{
//*****problem
if(???????? )
break;
else
userArray.add(scan.nextInt());
}
System.out.println("The array you entered is: " + userArray.toString() +"\n");
rotateArray(userArray);
System.out.println("When your array is rotated, it looks like this: \n" +
userArray.toString());
}
public static ArrayList<Integer> rotateArray(ArrayList<Integer> userArray)
{
int replace = 0;
int inc = 1;
int indexVariable = 0;
//if number of elements equals an even number
if(userArray.size() % 2 == 0)
{
for(int i = 0; i < (userArray.size()/2);i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
//if number of elements equals an odd number
else
{
for (int i = 0; i <(userArray.size()/2) ; i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
return userArray;
}
The thing about the scanner is that when its reading from the console, #hasNext will only ever return false if the scanner is closed, such as when you close it or the console is no longer usable for input. Otherwise, calling it will tell the scanner to wait for input and will let you know if it is valid input (e.g if you call #hasNextInt).
So the best way IMO to solve your issue is to read the scanner as a string, then split it and process it yourself as follows.
String input=scan.nextLine();
String[] numbers=input.split(" ");
for(String number:numbers)
{
if(number.isEmpty())
continue;//check for trailing so input like 3 4 5 is read
userArray.add(Integer.parseInt(number));//You would want to add a catch here for invalid input.
}
If input: 1 2 3 4 5 and userArray.size should match original.length then you can do like this:
int size = original.length;
for (int i = 0; i < size; i++) {
int num = scan.nextInt();
userArray.add(num);
Or you can hardcode variable size:
int size = 9;
or input it from console:
int size = scan.nextInt();

How to continue looping while the condition is false

I want my program to do the certain code only if the actors variable is <=5 && >0
else I want to go back and ask different question again:
System.out.println("\nEnter actors number(max.5): ");
int actorsNumber = scanner.nextInt();
scanner.nextLine();
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
So when the condition is false for example actors number = 7 then I want to tell the user: "Enter the valid actors number(1-5)" and do the for loop again if the actorsnumber is 1-5 instead ask again "Enter the valid actors number(1-5)"
You need to ask user to enter number in a loop. The condition of the loop will be the condition of your if. Then after exiting the loop (which means user enter a correct number), enter your for loop.
This will look like that :
int actorsNumber = -1; //force a wrong value at the beginning
while(actorsNumber < 1 || actorsNumber > 5) {
//Ask user to enter a number between 1 and 5
//store this number in actorsNumber
}
//As we exited the while-loop, actorsNumber is between 1 and 5
//Put your for-loop here
while(!scanner.nextLine().equals("quit")) {
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
}
Or something like that, point is, use a while loop on the scanner.
As #apexlol stated, your code should be in a loop. However, do-while loop is more convenient than while loop since that way, the loop executes at least once no matter what.

Two-Dimensional Array of contacts (Java)

I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}
Try like this for(j = 0; j < personalInfo[i].length; j++){
First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.
You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}

Categories

Resources