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
Related
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++;
The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, for example " This is a test" produces this results:
This is a test
1 letter words: 1
2 letter words: 1
3 letter words: 0
4 letter words: 2
5 letter words: 0
The bit that I'm stuck on is producing a mean/average, My guts telling to divide
counts.length by str.length but I'm not the Best at java and I've tried to implement this but all I get are errors. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Text_AD {
public static void main (String[] args) {
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}}}
By average, I am assuming that you mean the mean length. I am also assuming you want to get a floating point mean. In which case you just need to divide the total of all the lengths in strings by the length of the array itself.
You could do something like the following;
int total = 0;
for(String s : strings) total += s.length();
System.out.println((double)total/strings.length);
I hope this helps.
Without breaking up your code much, you could run a for loop through your counts[] array, adding up all the values, and then dividing by counts.length to get the average.
Be aware of type casting though. You may want to do Double division instead of integer.
It this what you are looking for?
import java.util.Scanner;
public class While_Loop {
public static void main (String[] args) {
int lengthSum, wordCount;
lengthSum = wordCount = 0;
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
wordCount++;
lengthSum += str.length();
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println("Average: " + lengthSum/wordCount);
}}}
NOTE: I only added stuff to your code. The way it is written is pretty messy. I'd clean up some of the for loops and the brackets at the end for practice making the code more readable.
When I understand you correct you should have one variable int totalCount = 0; where you add
totalCount += i*counts[i]; in your last for loop.
After the loop you can simply divide through the size-1 (because 0 does not count)
double average = totalCount/(counts.length-1);
Alternative way
You take the inputstring length without the spaces and divide it by the number of spaces + 1 (which is equal to the number of words)
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
System.out.println("Enter text: ");
String s = "This is a sample text";
System.out.println("" + s);
String[] strings = s.split(" ");
for(String str : strings) {
Integer counter = map.get(str.length())==null?0:map.get(str.length());
map.put(str.length(),counter++);
}
Integer sum=0;
Integer counter=0;
for(Integer len : map.keySet()) {
sum+=len*map.get(len);
counter+=map.get(len);
}
Double average = Double.valueOf(sum/counter);
Or you can combine the loops
Few suggestions which might help you (not related to the specific question).
Choose a meaningful class name rather than While_Loop .
Do, Scanner input = new Scanner(System.in); before the start of the loop.
As soon as you read each line, do the following.
Split the line using "\\s+" .
Create a HashMap with Key as Count (Integer) and Value as a list of Words with that count. Create this outside the loop.
For each split word,,get the length . and check if the map already contains the count, get the list (value), add he current word to it. else, add a new entry with the word as the single entry in the list.
Get the keySet of the map, add values of all keys i.e, *count * number of elements in the list*. then divide by total number of elements.
And yes, I know this is a very big change (something you might as well ignore..). But this is the right way to go.
so I am to write a method through Java that will read a file input, print a string that is a name, and sum up golf scores. I am literally stumped and can not think of how to do this. I have a main method that has been given and is not to be altered. This leaves me with another method to do all the work. Thus far I have,
public static void computeScores(Scanner file) {
int numGolfers = file.nextInt();
// add your code here
int highScore;
int totalScore = 0;
boolean beatPar;
beatPar = totalScore <= 72;
System.out.print("Number of golfers: " + numGolfers + "\n\n");
System.out.println("NAME SCORE TO PAR");
System.out.println("---- ----- ------");
for (int i = 1; i <= numGolfers; i++) {
String golferName = file.next();
boolean isLineOver = golferName == "\n";
while (isLineOver) {
int score = file.nextInt();
if () {
totalScore += score;
}
System.out.print(totalScore);
}
String nextGolfer = file.nextLine();
System.out.println(golferName + " " + totalScore);
//System.out.println(nextGolfer);
}
if (beatPar) {
System.out.println("At least one golfer scored par or below.");
}
}
I have only been able to output the names, and sometimes the first number from a list of 18 numbers. Sorry about the extraneous code that's been commented out.
Any kind of pointers would be appreciated.
The file I have been given has information in the following format
Name 1 2 3 4 5 etc.
change golferName == "\n" to golferName.equals("\n") for Strings
This question already has an answer here:
Odds and Evens Applications
(1 answer)
Closed 8 years ago.
How can I display all the evens on one line and all the odds on the next line? need to display 25 integers.
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
System.out.print ("EVENS & ODDS");
for(int i=0; i < 25; i++)
{
numbers [i] = (int) (Math.random()*99) + 1;
if(numbers[i]%2 == 0)
System.out.println(numbers[i] +" " );
else
System.out.println(numbers[i] +" " );
}
}
}
Instead of printing each number immediately, consider building up two strings (the first made up of the evens, and the second the odds). Then print the result strings when you're done. This should require just one loop.
In your providing code you print every number at time when it processed.if you want to print in one line so one possible solution is that you have store numbers in some array, or a string instead of display the number.
So in your code this line must change
System.out.println(numbers[i] +" ");
like this (if you want to store them in string variable)
even += numbers[i] +" ";
and later when loops end you can print out both line one by one.
Hope this will help you
//Snippet
if(numbers[i]%2 == 0)
even += numbers[i] +" ";
else
odd += numbers[i] +" ";
//after loops ends
System.out.println(even);
System.out.println(odd);
Just save all the evens in one array and all the odds in another and then print them seperately.
Well right now you are printing them all individually. what you could do is before the for loop declare a String for the odds and a String for the evens. and initialize them to "". then in the for loop instead of printing, just add the numbers[i] to the string and print them outside of the for loop
Alternatively ...
Read the javadoc for PrintStream, 'cos System.out is a PrintStream. Look at the different print methods available.
Create a string to hold them and just display them at once at the end:
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
String evens = "";
String odds = "";
System.out.print ("EVENS & ODDS");
for(int i = 0; i < 25; i++)
{
numbers [i] = (int) (Math.random() * 99) + 1;
if(numbers[i] % 2 == 0)
evens += numbers[i] + " "; // save it to evens string
else
odds += numbers[i] + " "; // save it to odds string
}
// now print them
System.out.println("Evens: " + evens);
System.out.println("Odds: " + odds);
}
}
The fragment of code which I'm about to post is from a program which is supposed to ask the user a series of multiple choice questions. The program will then keep score for each question and have a total which will be stored in another array. I will have multiple players playing this, so that's why i will need 2 arrays.
Here is what i have:
//Asks questions and stores score in array
public static int [] questions ()
{
userinput=""; //input will be stored in here
int total[]= new int[100];
int score[]=new int[5];
for(int i=0; i < ps.length; i++)
{
userinput=JOptionPane.showInputDialog(que[i]); //Outputs a question stored in another array in another method.
if (response.equals(ans[i])) //this compares the user input to the correct answer of the question, which is in another method.
{
JOptionPane.showMessageDialog(null,"You selected " + " " + ans[i] + " You were correct, 1 point!");
score[i]=1;
total[i]=total[i]+score[i];
}
else if(!response.equals(ans[i])) // If the answer isn't correct
{
score[i]=0; // I want to assign 0 for the question
JOptionPane.showMessageDialog(null,"You're wrong!, The correct answer was "+ans[i]);
}
} // close loop
return total; // return's this to another method which will do all of the other work
}
I seem to be having the problem here:
JOptionPane.showMessageDialog(null,"You selected " + " " + ans[i] + " You were correct, 1 point!");
score[i]=1;
total[i]=total[i]+score[i];
I want to add 1 to each element in score[] if the answer is correct. Then i want to accumulate the total of score[] and store that in each element of total[]. I return total to another method which stores it in an array.
Okay, so it seems you need to pass ordinal of current user in your method, so it can calculate correct position inside total array. Since it seems you want to aggregate total scores across multiple question/answer sessions, you need to pass total from outside:
public static void questions(int userOrdinal, int[] total) {
final int questionsPerUser = 5;
userinput = ""; //input will be stored in here
for (int i = 0; i < questionsPerUser; i++) {
userinput = JOptionPane.showInputDialog(que[i]); //Outputs a question stored in another array in another method.
if (response.equals(ans[i])) //this compares the user input to the correct answer of the question, which is in another method.
{
JOptionPane.showMessageDialog(null, "You selected " + " " + ans[i] + " You were correct, 1 point!");
total[userOrdinal * questionsPerUser + i] = 1;
} else if (!response.equals(ans[i])) // If the answer isn't correct
{
total[userOrdinal * questionsPerUser + i] = 0;
JOptionPane.showMessageDialog(null, "You're wrong!, The correct answer was " + ans[i]);
}
} // close loop
}
Sorry, I still can't get why you need score array, since your initial code is the same as total[i]++ and you never read contents of score, only write to it.