I'm a student just starting out in Java; I get hung up on seemingly easy concepts and have had trouble finding the answer to this despite a lot of googling. The assignment asks to:
Prompt the user to enter the number of people
Create a String array of the given size
Prompt the user for the name of each person
Put each name in the String array you created
Use a Java for-each to print each name with the length of the name
The output should look something like:
"Person 1 is named Andrew, and their name is 6 characters long"
This is what I currently have coded.
System.out.print("Hello. Please enter the number of people: ");
int people = scan.nextInt();
String[] myPeople = new String[people + 1];
System.out.println("Enter the name of each person:");
for(int i = 0; i < myPeople.length; i++)
{
myPeople[i] = scan.nextLine();
}
for(String peoples : myPeople)
{
System.out.println(peoples);
}
As it stands right now, the program can collect input from the user, put it into an array, and then print the array back out.
Am I approaching this the wrong way? I can't think of how I would modify the last For to not just print all the names, and instead print out each one with the "Person X is named ... ", their name, and then the description of how many characters long their name is.
Read about string concatenation.
int j = 1;
for(String peoples : myPeople)
{
System.out.println("Person " + j + " is named " + peoples + " and their name is " + peoples.length() + " characters long");
j++;
}
+ operator is used for concatenation of the strings.
You are doing good. In last for loop you can just do something like:
int personNumber = 0;
for(String people: myPeople)
{
System.out.println(String.format("Person %d is named %s, and their name is %d characters long", personNumber + 1, people, people.length());
personNumber++;
}
And one thing I've noticed - why are you instantiating array using new String[people + 1]? Why this extra one person? Arrays indexes are numered from 0, so new String[5] would give you array of 5 persons.
Firstly, you should create an array of size people, not people + 1:
String[] myPeople = new String[people];
To produce output in the required the format, you need to use the + operator to join the strings together. Also, since the person's position in the array is required, you need to create a variable to store that:
int index = 1;
for (String person: myPeople) {
String output = "Person " + index + " is named " + person + ", and their name is " + person.length() + " characters long.";
System.out.println(output);
index++;
}
Alternatively, you can use print instead of println: (only showing code inside for loop)
System.out.print("Person ");
System.out.print(index);
System.out.print(" is named ");
System.out.print(person);
System.out.print(", and their name is ");
System.out.print(person.length());
System.out.println(" characters long.");
index++;
Related
I have the following code, and I would like the user inputs to store, and then the code loop back with the next input storing also, until they hit "Q" which will then quit. I am not sure how to do it.
Also, I want my 2d array to be printed blank, instead of the default 0s, after the user sets the size. SO if the user says they want to input SIZE = 4x4 "row =1, column =2, input =7" it would print "These ZEROS would be BLANK
0000
0070
0000
0000
the input "row 2, column 1, input A it would print
0000
0070
0700
0000
My code so far
import java.util.*;
public class MainProg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many rows do you want for your matrix? ");
int row = in.nextInt();
System.out.print("How many columns do you want for your matrix? ");
int column = in.nextInt();
String[][] newArray = new String[row][column];
Array2 twoDArray = new Array2(row, column, newArray); //calling my class
do {
System.out.println("If you would like to set an, element press S: " + "\n" +
"If you would like to set an element, press G" + "\n" +
"If you would like to empty an element, press E" + "\n" +
"If you would like to print an element, press P" + "\n" +
"If you would like to quit, press Q");
String userInput = in.next();
if (userInput.equalsIgnoreCase("S")) {
twoDArray.setElement();
} else if (userInput.equalsIgnoreCase("G")) {
twoDArray.getElement();
} else if (userInput.equalsIgnoreCase("E")) {
twoDArray.clearElement();
} else if (userInput.equalsIgnoreCase("P")) {
twoDArray.printMatrix();
//you will do you toString here
} else if (userInput.equalsIgnoreCase("Q")) {
//this will quit the program
twoDArray.quitProgram();
}
//break;
} while (true);
}
}
import java.util.*;
public class Array2 {
MainProg main1 = new MainProg();
Scanner in = new Scanner(System.in);
private String [][] newArray;
private int row;
private int column;
public Array2(int row, int column, String[][] newArray) {
this.row = row;
this.column = column;
this.newArray = newArray;
}
public void getElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like to get in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to get in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
String getElement = newArray[userRow-1][userCol-1];
System.out.println(getElement);
}
public void setElement() {
System.out.println("What row would you like your element in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column would you like your element in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("What character would you like the element to be?");
String userChar = in.next();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[userRow][userCol] = String.valueOf(userChar);
}
public void clearElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like empty? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to empty? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
}
public void printMatrix() {
Scanner in = new Scanner(System.in);
//String result = " ";
System.out.println("The array is: \n");
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) {
System.out.print(newArray[i][j]);
}
//for (String[] row: newArray) THIS LEAD TO A PROBLEM
// Arrays.fill(row, " ");
System.out.println();
}
}
public void quitProgram() {
System.out.println("The system will now exit! BYE!!!");
System.exit(0);
}
}
I have EDITED my code so that I have answered some questions. Now my only problem left is getting my matrix to be initially filled with blanks " ", instead of the default "null". I attempted to use the Arrays.fill in my printMatrix method, however that lead to problems, it would not save the user input after the loop.
Your IndexOutOfBoundsException (now editted out) is due to you using row and column instead of userRow and userColumn in setElement, which are where you've stored the user inputs. row and column will refer to the classes member variables, which are both 5 since you set it up as a 5x5 matrix, so above the max index of 4. You also will need to conver the char to a string since your using a String[][]
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[row][column] = userChar;
The last line should be newArray[userRow][userColumn] = String.valueOf(userChar);. Though you probably want to check those values are less than row and column to avoid more of that exception.
Even with that fixed, your code currently has other issues. The biggest is that you're currently defininig and using a new array in most methods and not the member variable newArray, so the method calls to get/set/clear/print aren't using your instance like you expect, but new empty arrays each time. These should be manipulating this.newArray not creating their own to manipulate, which dies with their return. You'll need to work through fixing all of that before looking into looping over the user input and interacting with your array.
On the printing of 0's, that is a side affect of one of the above issues. In printMatrix you declare a new int[][] newArray and print that. The default value of int is 0, so you get all 0's. If you were using your String array you'd get all "nullnullnull.." for each row as String's default to null. If you want all blanks initially, you'll have to initalize the array to all empty strings in your constructor or handle the null when looping through the array printing a space instead.
On looping for user input, you'll also need to ask for it again inside of your loop before the while, as otherwise the user input will only be asked for once and you will forever loop with that option.
Good luck, this seems like a good excersize to familiarize yourself with OO and array maniupulation, but a lot of the issues in your code are outside the scope of a single SO answer and smells a bit like classwork. I got your example code fixed up and manipulating as you want with only a handful of changes, so youre close.
EDIT:
In the future, please don't continuously edit questions to reflect further development unless you leave the original in place and add to it and it still reflects a continuation of the original problem, as it makes answers and comments have no context. SO is meant more to be questions and answers about specific issues faced, not a forum for feedback on continued development. If you got past a specific problem via an answer, mark that answer as the solution and move any new issues into a new question, else you risk having your question closed. See the first few topics under https://stackoverflow.com/help/asking, especially https://stackoverflow.com/help/how-to-ask, to see what I mean. I'm being pretty gentle, but this community can not always be.
That being said, as you seem to be making a geniune effort here, here's a few more bits of advice based on your comments and edits.
If you want to prefill the rows with spaces, the
for (String[] row : newArray)
Arrays.fill(row, " ");
block of code would not go in print, as that would blank it out each time print is called. It should go into your constructor, so that it only happens once when the object is created.
Alternatively, if you wanted to deal with it in the print method, something like
System.out.print(newArray[i][j] == null ? " " : newArray[i][j]);
Would do the trick, using a ternary operator to print out " " instead of null when encountered.
You also don't need to new up the Scanner in those methods but its not affecting functionality.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 2 years ago.
I've decided to learn some java. I've come across something that doesn't seem to make much sense. An array gets permanently modified after being passed to a method.
This little project works pretty good. The project passes an array having a middle name to a method which corrects the middle name. The middle names getting passed to the method have only a middle initial. The method replaces the middle initial with the full middle name.
A name can have different lengths from 3 to more elements. A name might include titles (Dr. Mr. Mrs, etc ), or the name might include a hyphened last-name, or a name might include a suffix (Jr, II, IV, etc .. ). But the name being passed will always include at least (first name, middle initial, last name). The method only replaces the middle initial with the full middle name.
There are 3 parameters passed to the method (the name array, a string holding the full middle name, and an integer 'position' that represents the index position of the middle-initial).
The method returns a Boolean value. If the user passes a bad position that is outside the length of the array, then the method immediately returns, false.
So ... all this said to ask one simple question: since the method only returns a Boolean value, how does the original array become permanently changed after it is passed to the method, yet oddly, the insert position does not get permanently change by the method ?
About the code: There are multiple redundant and unnecessary lines of code to print the code as the code gets executed. The java code is in two different java files (the main method file, the method file ).
Code main method:
import java.util.Scanner;
public class MiddleName {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter array length:");
int len = scan.nextInt();
scan.nextLine();
String[] wordList = new String[len];
System.out.println("Enter values:");
for(int i = 0; i < len; i++){
wordList[i] = scan.nextLine();
}
System.out.println("\n" + "The values entered were: ");
for( String e: wordList) {
System.out.println(e);
}
System.out.println("\n");
// ============================================================
System.out.println("Enter the replacement String:");
String replace = scan.nextLine();
System.out.println("Enter the replacement position:");
int pos = scan.nextInt();
// method call with parameters);
System.out.println("Method return: " + other.insert(wordList, replace, pos));
// Prints the returned array (with the changes)
System.out.print("Array contents: {");
for(int i = 0; i < len; i++){
System.out.print(wordList[i] + ", ");
}
System.out.println("}");
System.out.println();
for(String e: wordList) {
System.out.println(e);
}
System.out.println("The returned pos value is: " + pos);
scan.close();
} // end main
} // end class
Code: Other
public class other {
// fields
public static boolean insert(String words [], String newWord, int place) {
boolean goNOgo = false;
int len = words.length;
System.out.println("\n" + "In the constructor method" + "\n");
for(String e: words) {
System.out.print(e + ", ");
}
System.out.println("\n" + "The insertion point is: " + place + ", and the replacement value is: " + newWord);
if(place > len) {
return false; // if the place > length of array, then all fails and return as: false
} else { // if the place value is not greater than array.lenght
for(int i = 0; i < place; i ++) {
}
}
words[place] = newWord; // insert the replacement word
System.out.println("\n"); // print the updated array
for(String e: words){
System.out.println(e);
}
System.out.println("\n" + "In method, the updated array value(s) are: " + "\n");
for(String e: words) {
System.out.print(e + " ");
}
System.out.println("\n");
place = 50;
goNOgo = true;
return goNOgo;
} // method
} // class
The code entered and the resulting output:
Enter array length:
4
Enter values:
Mr
John
D
Doe
The values entered were:
Mr
John
D
Doe
Enter the replacement String:
David
Enter the replacement position:
2
In the constructor method
Mr, John, D, Doe,
The insertion point is: 2, and the replacement value is: David
Mr
John
David
Doe
In method, the updated array value(s) are:
Mr John David Doe
Method return: true
Array contents: {Mr, John, David, Doe, }
Mr
John
David
Doe
The returned pos value is: 2
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Hi developers on Stackoverflow! I have a problem on this exercise:
"Write a program that asks user to input a list of N names using the keyboard, then user continues
inputting a name for searching. The program should print out the position of this name in the list.
In case the name doesn’t appear in the list, the program should print out value -1."
Here is my code:
package Tut_01;
import java.util.ArrayList;
import java.util.Scanner;
public class Ex_04 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
ArrayList<String> elements = new ArrayList<> ();
System.out.print ("How many numbers do you want to input: ");
int n = sc.nextInt (); // Count numbers that user want to input
// Ask the user input values
for (int i = 0; i < n; i++) {
System.out.print ("Enter your name " + (i + 1) + ": ");
String name = sc.next ();
elements.add (name);
}
System.out.println ("Which name do you want to search ?");
String searchName = sc.next ();
// Problem?
for (int p = 0; p < n; p++) {
if (searchName == elements.get (p)) {
System.out.println ("Your name is at index " + p + ": " + elements.get (p));
}
}
}
Here is my console:
How many numbers do you want to input: 2
Enter your name 1: Hoa
Enter your name 2: Hieu
Which name do you want to search ?
Hoa
Process finished with exit code 0
I mean I don't know why my code stops there instead of printing the position of the index. Anyone knows this issue? Thanks for showing me!
You are comparing String in the wrong way. String is an object not a primitive, so you cannot use ==.
The proper way is:
searchName.equals(elements.get(p))
Below the simple code will give the same output.Make use of indexOf method
System.out.println("Your name is at index " + elements.indexOf(searchName) + ": " + searchName);
This question already has answers here:
How to convert string array to int array in java [duplicate]
(6 answers)
Closed 6 years ago.
I am making a code that stores sport scores and matches through user input however I have used a string array to store both string and int value - while this did not seem to be a problem at first I have realized that validation becomes tedious as you can equally store a string in the "score" section even though it is incorrect.
I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem.
The user input looks like this;
Home_Team : Away_Team : Home_ Score : Away Score
I want to be able to add all the Away/Home scores to produce an output like so;
Total Home score: x
Total Away Score: x
Here is my for loop so far,
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input
if (words.length == 4) {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["+ words[3].trim() + "]");
}else{
System.out.println("Your input was not valid.");
matches--;
invalid++;
The logic for my new code will be "If Element[] does not contain an int value print "Invalid input"
"I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem."
To make an integer from a String, use this :
int x = Integer.parseInt( some_string );
Java Split String Into Array Of Integers Example
public class Test {
public static void main(String[] args) {
String sampleString = "101,203,405";
String[] stringArray = sampleString.split(",");
int[] intArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
String numberAsString = stringArray[i];
intArray[i] = Integer.parseInt(numberAsString);
}
System.out.println("Number of integers: " + intArray.length);
System.out.println("The integers are:");
for (int number : intArray) {
System.out.println(number);
}
}
}
Here is the output of the code:
Number of integers: 3
The integers are:
101
203
405
I just started learning Java and I'm having trouble formatting string. In the problem I have a string a user inputted that is a name in the format: "First Middle Last". I need to output the string in the format: "Last, First MI. " (MI is middle initial).
Here is what I have so far, I have the first name working, but unsure how to go about getting the last and middle initial out of the string.
// Variable declarations
String name, first, last, middle;
Scanner scan = new Scanner (System.in);
// Get name from user in format "First Middle Last"
System.out.println("Enter the person's name: ");
name = scan.nextLine();
// Get first, middle initial, and last name from the string
first = name.substring(0, name.indexOf(" "));
middle =
last =
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middle + ".");
so for example if the user entered: "John Robert Doe", it would output as "Doe, John R."
Any help is appreciated.
You can use the split method of the String class
// Get first, middle initial, and last name from the string
String nameParts [] = name.split(" ");
// not sure if you need these variables, but I guess you get the picture
first = nameParts [0];
middle = nameParts [1];
last = nameParts [2];
middleInital = middle.charAt(0);
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middleInital + ".");
Take a look at the String.split method. This allows you to find the substrings. Then you only have to place them in the correct order
Take a look at String split and charAt method of String class.
String person_data = "John Robert Doe" ;
String[] data = person_data.split(" ");
char MI = data[1].charAt(0);
System.out.println(data[2] +","+ data[0] + " "+ MI);
Output = Doe,John R
Here
Data[0] == "John"
Data[1] == "Robert"
Data[2] == "Doe"
MI = first character of Data[1] which is R.
Try this:
String name = "First Middle Last";
String[] data = name.split(" ");
String formatted = String.format("%s, %s %c.", data[2], data[0], data[1].charAt(0));
The last line assigns the value "Last, First M." to the variable formatted, as expected. This solution makes use of Java's Formatter class, which is a big help for all your string formatting needs.
You will need to first split the string (using String.split) and then format it.
Forgive me since I'm typing this on my iPad, the answer will look as follows:
String names = name.split("\\s+"); \\Split on whitespaces, including tab, newline and carriage return.
StringBuilder sb = new StringBuilder();
for (int x = 0; x < names.length; x++) {
switch (x) {
case 0: sb.apppend(names[names.length - 1]).append(", ");
break;
case 1: sb.append(names[0]).append(" ");
break;
case 2: sb.append(Character.toUpperCase(names[1].charAt(0))).append(".");
break;
default: break;
}
}
String fullName = sb.toString();