Multiple inputs with arrays - java

I need to write a program that helps determine a budget for "peer advising" the following year based on the current year. The user will be asked for the peer advisor names and their highest earned degree in order to determine how much to pay them. I am using a JOptionPane instead of Scanner and I'm also using an ArrayList.
Is there a way for the user to input both the name and the degree all in one input and store them as two different values, or am I going to have to have two separate input dialogs? Example: storing the name as "Name1" and the degree as "Degree1 in order to calculate their specific pay.
Also, I am using an ArrayList but I know that the list will need to hold a maximum of six (6) elements, is there a better method to do what I am trying to do?
Here is what I had down before I started thinking about this, if it's necessary.
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> tutors = new ArrayList<String>();
for (int i = 0; i < 6; i++)
{
String line = null;
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
String[] result = line.split("\\s+");
String name = result[0];
String degree = result[1];
}
}
}

"Is there a way for the user to input both the name and the degree all
in one input, but store them as two different values."
Yes. You can ask the user to enter input separated with space for example, and split the result:
String[] result = line.split("\\s+"); //Split according to space(s)
String name = result[0];
String degree = result[1];
Now you have the input in two variables.
"I decided to use ArrayList but I know the number of names that will be inputed (6), is there a more appropriate array method to use?"
ArrayList is fine, but if the length is fixed, use can use a fixed size array.
Regarding OP update
You're doing it wrong, this should be like this:
ArrayList<String[]> list = new ArrayList<String[]>(6);
String[] splitted;
String line;
for(int i=0;i<6;i++) {
line = JOptionPane.showInputDialog("Please enter tutor name and their highest earned degree.");
splitted = line.split("\\s+");
list.add(splitted);
}
for(int i=0;i<6;i++)
System.out.println(Arrays.deepToString(list.get(i))); //Will print all 6 pairs
You should create an ArrayList that contains a String array that will represent the input (since the user enters pair as an input). Now, all what you have to do is to insert this pair to the ArrayList.

What you can do is store the input from you JOptionPane in a String, and then split the String into an array to store the name and degree entered. For example:
String value = null;
value = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] tokens = value.split(" ");//if you input name followed by space followed by degree, this splits the input by the space between them
System.out.println(tokens[0]);//shows the name
System.out.println(tokens[1]);//shows the degree
Now you can use tokens[0] to add the name to your List.

Related

How can I obtain the first character of a string that is given by a user input in java

I want the user to input a String, lets say his or her name. The name can be Jessica or Steve. I want the program to recognize the string but only output the first three letters. It can really be any number of letters I decide I want to output (in this case 3), and yes, I have tried
charAt();
However, I do not want to hard code a string in the program, I want a user input. So it throws me an error. The code below is what I have.
public static void main(String args[]){
Scanner Name = new Scanner(System.in);
System.out.print("Insert Name here ");
System.out.print(Name.nextLine());
System.out.println();
for(int i=0; i<=2; i++){
System.out.println(Name.next(i));
}
}
the error occurs at
System.out.println(Name.next(i)); it underlines the .next area and it gives me an error that states,
"The Method next(String) in the type Scanner is not applicable for arguments (int)"
Now I know my output is supposed to be a of a string type for every iteration it should be a int, such that 0 is the first index of the string 1 should be the second and 2 should be the third index, but its a char creating a string and I get confused.
System.out.println("Enter string");
Scanner name = new Scanner(System.in);
String str= name.next();
System.out.println("Enter number of chars to be displayed");
Scanner chars = new Scanner(System.in);
int a = chars.nextInt();
System.out.println(str.substring(0, Math.min(str.length(), a)));
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
Instead, use code point integer numbers to work with individual characters.
Call String#codePoints to get an IntStream of the code point for each character.
Truncate the stream by calling limit while passing the number of characters you want.
Build a new String with resulting text by passing references to methods found on the StringBuilder class.
int limit = 3 ; // How many characters to pull from each name.
String output =
"Jessica"
.codePoints()
.limit( limit )
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString()
;
Jes
When you take entry from a User it's always a good idea to validate the input to ensure it will meet the rules of your code so as not to initiate Exceptions (errors). If the entry by the User is found to be invalid then provide the opportunity for the User to enter a correct response, for example:
Scanner userInput = new Scanner(System.in);
String name = "";
// Prompt loop....
while (name.isEmpty()) {
System.out.print("Please enter Name here: --> ");
/* Get the name entry from User and trim the entry
of any possible leading or triling whitespaces. */
name = userInput.nextLine().trim();
/* Validate Entry...
If the entry is blank, just one or more whitespaces,
or is less than 3 characters in length then inform
the User of an invalid entry an to try again. */
if (name.isEmpty() || name.length() < 3) {
System.out.println("Invalid Entry (" + name + ")!\n"
+ "Name must be at least 3 characters in length!\n"
+ "Try Again...\n");
name = "";
}
}
/* If we get to this point then the entry meets our
validation rules. Now we get the first three
characters from the input name and display it. */
String shortName = name.substring(0, 3);
System.out.println();
System.out.println("Name supplied: --> " + name);
System.out.println("Short Name: --> " + shortName);
As you can see in the code above the String#substring() method is used to get the first three characters of the string (name) entered by the User.

Getting and Printing User Inputs in HashMaps in Java

I stepped into Java one month ago, and have been studying then. I've come across with a problem. I need to get N number of user input pairs (key:value) to a HashMap in Java, as mentioned in below code. This gives me an InputMismatchException after entering one key:value pair. For the best of my knowledge, I can't figure out whether there is a syntax error in declared loops and assigning user input value pairs to declared HashMap. I will be really grateful if someone can elaborate this, hopefully in simple terms, as I'm a very beginner. Thank you so much for your concern.
public static void main (String [] arg){
HashMap<String, Integer> phonebook = new HashMap<>();
Scanner obj = new Scanner(System.in);
//N= Number of contacts to be entered by the user
int N = obj.nextInt();
//Getting N num of user inputs for names and contacts
while(N>0){
for (int i=0;i<N;i++)
{
//we need to input name and contact value pairs
//in same line
String name = obj.nextLine();
int contact = obj.nextInt();
//assigning user input key:value pairs to hashmap
phonebook.put(name, contact);
}
//setting key:value pairs to display
Set<String> keys = phonebook.keySet();
for(String i:keys)
{
System.out.println(i +"="+phonebook.get(i));
}
N--;
}
}
You always need to put obj.nextLine(); after you do obj.nextInt();. This is because obj.nextInt(); only consumes the number, but when you enter a number and hit the enter key, the input stream also records a newline character at the end, so the next obj.nextLine(); picks up an empty string, and you are always off by one from then on. Here's an example sequence of events:
You enter the number of inputs.
The program reads that into the variable N.
The program reads the remaining empty string into the variable name.
You enter the name.
the program tries to read a number into the variable contact, but what you entered is not a number, so it fails.
And for your own sanity, please use some indentation. Here is your corrected code, with indentation:
public static void main(String[] arg) {
HashMap<String, Integer> phonebook = new HashMap<>();
Scanner obj = new Scanner(System.in);
//N= Number of contacts to be entered by the user
int N = obj.nextInt();
obj.nextLine(); //consume the newline
//Getting N num of user inputs for names and contacts
while (N > 0) {
for (int i = 0; i < N; i++) {
//we need to input name and contact value pairs
//in same line
String name = obj.nextLine();
int contact = obj.nextInt();
obj.nextLine(); //consume the newline
//assigning user input key:value pairs to hashmap
phonebook.put(name, contact);
}
//setting key:value pairs to display
Set<String> keys = phonebook.keySet();
for (String i : keys) {
System.out.println(i + "=" + phonebook.get(i));
}
N--;
}
}
Or, if you actually want both the name and the contact to be entered on the same line as you say in the comments, you can replace this line:
String name = obj.nextLine();
With this line:
String name = obj.findInLine("\\D+");
This just tells Java to read from the input stream until it hits a digit character.
You need to add an obj.nextLine() statement after getting N. When you enter something in a prompt, there's an end-of-line character that gets added after you press enter (\n). nextInt() only reads a number, so when you call nextLine() immediately after nextInt(), it will just read the end-of-line character \n because nextInt() didn't pick it up. By adding an extra nextLine() statement after calling nextInt(), you get rid of the \n and the program can read the values properly.
This code works:
public static void main (String [] arg){
HashMap<String, Integer> phonebook = new HashMap<>();
Scanner obj = new Scanner(System.in);
//N= Number of contacts to be entered by the user
int N = obj.nextInt();
obj.nextLine();
//Getting N num of user inputs for names and contacts
while(N>0){
for (int i=0;i<N;i++)
{
//we need to input name and contact value pairs
//in same line
String name = obj.nextLine();
int contact = obj.nextInt();
obj.nextLine();
//assigning user input key:value pairs to hashmap
phonebook.put(name, contact);
}
//setting key:value pairs to display
Set<String> keys = phonebook.keySet();
for(String i:keys)
{
System.out.println(i +"="+phonebook.get(i));
}
N--;
}
}
Console input and output is below. You might want to use i < N - 1 and not i < N, because I wanted to input 2 contacts only, but had to add 3. This may confuse the user.
2
foo
100
bar
1000
bar=1000
foo=100
n
1000000
bar=1000
foo=100
n=1000000

Copy a string of words to an array in Java

Ive been writing a program that is able to calculate a person's grades, but Im unable to turn a string into an String array (it says the array length is 1 when i put in 3 words). Below is my code. Where am I going wrong??
protected static String[] getParts(){
Scanner keyboard = new Scanner(System.in);
System.out.println( "What assignments make up your overall grade? (Homework, quizzes, etc)" );
String parts = keyboard.next();
Pattern pattern = Pattern.compile(" ");
String[] assignments = pattern.split(parts);
// to check the length
for ( int i = 0; i < assignments.length; i++ )
System.out.println(assignments[i]);
return assignments;
}
Scanner::nextLine
Scanner::next() only consumes one word (it stops at whitespace). You want Scanner::nextLine, which consumes everything until the next line, and will pick up all your words.
Use keyboard.nextLine instead:
static String[] getParts()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What assignments make up your overall grade? (Homework, quizzes, etc)");
String[] assignments = keyboard.nextLine().split(" ");
for (String i : assignments)
System.out.println(i);
return assignments;
}
NOTE: You also do not need to define a Pattern. You also do not need to return anything since the method already prints the strings. Unless of course you plan on using the values elsewhere

How to insert a String into a String array in java?

I have the following code that gets a user input:
456589 maths 7.8 english 8.6 end
654564 literature 7.5 physics 5.5 chemistry 9.5 end
and stores the code at the beginning of the sentence in an array called grades and the code in another array called person. I need to use these two arrays in order to display later each person's average grade in each lesson.
My code is the following
import java.util.Scanner;
public class Student
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
String am = "";
String subj = "";
float grad;
float[] grades = new float[100];
String[] person = new String[100];
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
while(!currentAnswer.equals("end"))
{
currentAnswer = s.nextLine(); // reads the number or word
userWords += currentAnswer + " ";
if(currentAnswer.equals("000000"))
{
System.out.println("The sequence of numbers you entered is: "+userWords);
System.out.println("Exiting...");
System.exit(0);
}
String[] wordsplit = currentAnswer.split(" ");
for (String str : wordsplit)
{
try
{
grade = Float.parseFloat(str);
}
catch(NumberFormatException ex)
{
person = str;
}
}
}
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
}
}
The error message concers the lines
grades = Float.parseFloat(str);
person = str` --> `String cannot be converted to String[]`<br>
Seems that converting a String into a String array is prohibited. What can I do in order to avoid this?
thank you!!
Look again on the code
grade = Float.parseFloat(str); and vars declaration
float grad; float[] grades = new float[100]
Cannot see any grade !
This cannot compile for sure !
Well, the error message speaks for itself, you are trying to assign String into String[], since it is an array, you want to call something like person[0] = str, same thing with grade, you want to call grade[0] = Float.parseFloat(str)
... but ofc you probably want to store number of persons inserted into the array, so you create an int inserted = 0 and then call grade[inserted] = Float.parseFloat(str) and also call inserted++ after that (or simply call grade[inserted++] = Float.parseFloat(str).. I assume you will need one integer for persons and one for grades
Try using ArrayLists, there are more forgiving than arrays, and simple to learn. You can see more about them here:
https://www.w3schools.com/java/java_arraylist.asp
If you want to use ArrayList, you must include this in begging of your file.
import java.util.ArrayList;
You defined grad and used grade
Initially when you defined you used the variable name grad
float grad;
But you used grade here
grade = Float.parseFloat(str);
Also try to use ArrayList instead of String array

Prompt user for inputs and then sort alphabetically?

I'm currently in my first semester. I have a project requiring me to build a program having a user input 3 words, sort them alphabetically and output the middle word. I have done some searching and seem to only come back with results for sorting 2 words. I so far have code to get the user input but I am completely lost as to how to sort them alphabetically and how to prompt the user to enter the three strings. Please be patient with me as I am very new to programming. If anyone can provide me with any advice or the best or easiest way to go about sorting these I would greatly appreciate it
import java.util.Scanner; //The Scanner is in the java.util package.
public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.
String str1, str2, str3;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
str1=input.next(); //Sets "str1" = to first word.
str2=input.next(); //Sets "str2" = to second word.
str3=input.next(); //Sets "str3" = to third word.
System.out.println("The middle word is " ); // Outputs the middle word in alphabetical order.
}
}
Please help!
Try something like this:
String [] strings;
int i = 0;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
strings[i++] = input.next(); //Sets "str1" = to first word.
strings[i++] = input.next(); //Sets "str2" = to second word.
strings[i++] = input.next(); //Sets "str3" = to third word.
Arrays.sort(strings);
System.out.println("The middle word is " + strings[strings.length / 2]);
You can sort (compare) only two words at a time, yes, but that is the basis for the whole sorting algorithm. You'll need to loop through your array of words and compare each word with each other word.
String[2] words = new String[2];
words[0] = input.next();
words[1] = input.next();
words[2] = input.next();
String[2] sortedWords = new String[2];
for (String word: words){ // outer loop
for (String word: words){ // inner loop to compare each word with each other
// logic to do the comparisons and sorting goes here
}
}
System.out.println(sortedWords[1]);
Of course I've left out the fun part for you, but that should get you started.

Categories

Resources