How to insert a String into a String array in java? - 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

Related

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 match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

Accumulate Strings in Loop and Print Out all of them

I am trying to figure out how to accumulate user inputs in for loop and then to print them out with one system.out.print. This is my test code for the problem.
So for example if a user type : Mike for his name and Joe,Jack,Dave for other names, how to print them all just having one variable because amount of variables are not known since a user has that decision. Also is it possible to do that without stringbuilder and without arrays?
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
String othernames = " ",name;
int count,n;
Scanner kybrd = new Scanner(System.in);
System.out.println("Enter your name ");
name = kybrd.nextLine();
System.out.println("How many other names would you like to add ? ");
count = kybrd.nextInt();
kybrd.nextLine();
for(n=0;n<count;++n){
System.out.println("Enter other names ");
othernames = kybrd.nextLine();
}
System.out.println("Other names are "+othernames + " And your name is "+ name);
}
}
You can call it recursively, for instance:
Scanner sc = new Scanner(System.in);
String s;
while(condition) {
s = s + sc.nextLine();
}
this will always concat the lines you enter, you can also add commas, or spaces, or whatever you want to add.
as for your question about using Objects other than StringBuilder you can use List<String> and build a string for it at the final step.
you can use Map<String, String> if you need more complex data structure.

Multiple inputs with arrays

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.

InputMismatchException while reading two lines correctly?

I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:
Daan Jansen M 1.78 83
Sophie Mulder V 1.69 60
It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:
package practicum5;
import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;
public class BodyMassIndex {
PrintStream out;
BodyMassIndex() {
out = new PrintStream(System.out);
UIAuxiliaryMethods.askUserForInput();
}
void start() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String lineDevider = in.nextLine(); //Saves each line in a string
Scanner lineScanner = new Scanner(lineDevider);
lineScanner.useDelimiter("\t");
while(lineScanner.hasNext()) {
String patientNames = lineScanner.next();
String patientSex = lineScanner.next();
double patientLength = lineScanner.nextDouble();
int patientWeight = lineScanner.nextInt();
}
}
in.close();
}
public static void main(String[] args) {
new BodyMassIndex().start();
}
}
Somebody got a solution for this?
Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.
Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.
One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.
Your name field has two token. and you are trying to treat them as one. that;s creating the problem.
You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.
I changed the dots to commas in the input file. Hooray.

Categories

Resources