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
Related
My program consists of several options of what to do with user input data about shows (name, day, time). One of the options is to display the data and the total number of shows per day (ex: if there are 2 shows on Tuesday, it will display "There are 2 shows on Tuesday"). So far the output for displaying all the data is working but when it comes to displaying the number of shows on a specific day, it isn't working properly. I've read several other java programs that seem to have a switch statement on each day but that hasn't worked either. If there are any suggestions on what I should change about my code, I would truly appreciate it! Thank you
I have edited my code from the previous one but it still hasn't worked
Note: the int dayCount is placed in the enter data method; after the day[i] = br.readLine();
Here is my class:
import java.io.*;
public class Javavision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String name[] = new String[1000];
static String day[] = new String[1000];
static String time[] = new String[1000];
static int dayCount = 0;
static int x, i, j, smallest;
static String temp;
Here is my code:
public static void showShows() {
//output all shows
for (i = 0; i < x; i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
} **The problem is here**
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
}
Here is the output:
Name : The Flash
Day : Sunday
Time(2:30 am = 0230) : 0125
Name : Suits
Day : Sunday
Time(2:30 am = 0230) : 0450
Name : Java Program
Day : Tuesday
Time(2:30 am = 0230) : 0330
There is 3 shows on Sunday
This is where I increment dayCount:
//Method addShow
public static void addShow() throws IOException {
//initialize counter
x = 0;
do {
//Update Array
System.out.println("Enter Name of Show: ");
name[x] = in.readLine();
System.out.println("Enter Day of Show: ");
day[x] = in.readLine();
dayCount++;
System.out.println("Enter Time of Show (ex: 2:30am = 0230) : ");
time[x] = in.readLine();
//Increase counter
x++;
//Ask if the user wants to stop
System.out.println("\nTo continue press Enter ");
System.out.println("To Quit, type in 'quit': ");
}
while((in.readLine().compareTo("quit"))!=0);
//Method addShow()
}
In your loop that prints the total shows you have:
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
The if(i == 0) makes it so that the println only executes on the first iteration of the loop. Take out the if statement and have:
for (i = 0; i < x; i++) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
And this should print out the rest of the days
Also you only have one dayCount variable that you use for all the days. So no matter what day a show is on, you increment dayCount. (If you have three shows on different days you still increment dayCount everytime so it shows that you have three shows on each day when you print it out) If you want to have a separate dayCount variable for every day, I recommend using a Hashmap.
(Using the day as the key and the dayCount as the value)
Also you could look into enums to use for the days of the week.
I am quite new to programming and I am writing this code to count a string (length) to a point when I encounter a space. The aim is - when the user enters his/her name AND surname, the program should split the name from surname and count how many letters/characters were there in the name (and surname).
My code doesn't seem to reach/execute the "if-statement", if I enter two strings (name & surname) separated by space (output: Your name is: (empty space) and it has 0 letters. However, if I enter only one string, the if-statement, it gets executed.
What I am doing wrong?
My example code:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
for(int x = 0; x<=nameAndSurname.length()-1; x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
scan.close();
}
Why bother with all that code? Just skip the for-loop, have an
if (space != -1) nameOnly = nameAndSurname.substring(0,space);
and if you really want to know the amount of letters, it is
space+1
No need for all that complicated stuff.
if(nameAndSurname.indexOf(x) == space)
This line isn't doing what you think it is doing.
It's getting a char (character) from the index of x, and comparing it to the value of space. Space is an integer, so you are comparing the character at position x to the integer position of the first space. In this case, the letter at position x is cast into an integer, and then compared to the actual number value of the first space!
To fix the program, replace your entire if statement with this.
if (nameAndSurname.charAt(x) == ' ') //if there is a space
{
count = c-1; //how many characters/letters was there before space
System.out.println(count);
}
Extra:
Since the way you've solved this problem is a bit overkill, I've posted another solution below which solves it in a way that is easier to read. Also it won't break if you put in more or less than 1 space.
Scanner scan = new Scanner(System.in);
String nameAndSurname;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine().trim();
int indexOfFirstSpace = nameAndSurname.indexOf(' ');
if (indexOfFirstSpace > -1) {
String firstName = nameAndSurname.substring(0, indexOfFirstSpace);
System.out.println("Your first name is " + firstName.toUpperCase());
System.out.println("It is " + firstName.length() + " characters long.");
}
You can verify if your string has space before start the loop, something like this:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
if(space == -1) {
System.out.println("Your name has no spaces");
} else {
for(int x = 0; x<nameAndSurname.length(); x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
}
scan.close();
}
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 am writing a program that takes a document created by one program by PrinterWriter and then hashes the lines in that document to an array in the new program. The hash is done by using the ASCII code for the letter and adding them up. I am able to get the correct hash for each line and save it in the hash table. By the way, it is a list of countries that is hashed. My problem is that it does not seem to be able to compare the countries entered by the user, even though it is copy and paste, to the ones in the hash table to display them. It is not only supposed to display the country in the hash table, but all the ones leading up to the hash table. So if one was supposed to go to spot 23 but went to spot 26, display 23-26 to show clustering. I have tired everything to get it to work, but nothing seems to work, please help. I have included some of the code:
import java.io.PrintWriter;
import java.io.File;
import java.util.*;
import java.text.*;
public class Hashing
{
String[] line = new String[238];
String[] HashTable = new String[300];
public Hash() {
for (int i = 0; i< HashTable.length; i++) {
HashTable[i]=null;
}
}
public void readIn()throws Exception {
Scanner ln = new Scanner(new File(System.getProperty("user.home"), "user.home.CountryUnSortedFormat.txt"));
int i = 0;
while (ln.hasNextLine()) {
line[i] = ln.nextLine();
i++;
}
}
public int toASCII(String input) {
int total = 0;
char character;
String str = input.replaceAll(",","").trim();
if (str.length() > 50) {
for (int i = 0; i<50; i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
} else if (str.length()<50) {
for (int i = 0; i<str.length(); i++) {
int ascii = str.charAt(i);
if (ascii > 32) {
total = total + ascii;
}
}
}
return total % 300;
}
public void hashIt(String input, int where){
int counter = where;
if (where==299 && HashTable[where]!=null){
counter = 0;
}
while (HashTable[counter]!=null){
counter++;
}
System.out.println("Country = " + input + " HashValue = " + where + " actual HashSpot = " + counter);
HashTable[counter]=input;
}
public boolean showCountries(String paramCountry, int where){
int location = where;
int length = paramCountry.length();
while (!(HashTable[location].substring(0,length).contains(paramCountry))){
System.out.println("Input = " + paramCountry + " and HashTableCOunty = " + HashTable[location].substring(0,length));
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
if (!(HashTable[location].substring(0,length).contains(paramCountry))){
location++;
}
else if (HashTable[location].substring(0,length).contains(paramCountry)){
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
System.out.println("Eguals");
return true;
}
if (location==300||HashTable[location]==null){
System.out.println("End");
return false;
}
}
return false;
}
public void displayHashTable() {
for (int i = 0; i<HashTable.length; i++) {
System.out.println("i = " + i + " " + HashTable[i]);
}
}
public static void main(String[]args)throws Exception {
Scanner kb = new Scanner(System.in);
Hash H = new Hash();
H.readIn();
for (int i = 0; i< 238; i++) {
int where = H.toASCII(H.line[i]);
H.hashIt(H.line[i], where);
}
H.displayHashTable();
String UserChoice;
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
while (!(UserChoice.equalsIgnoreCase("-1"))) {
int index = H.toASCII(UserChoice);
boolean error = H.showCountries(UserChoice, index);
while (error == false) {
System.out.println("The country you searched for is not in the hash table. Try again.");
UserChoice = kb.nextLine();
index = H.toASCII(UserChoice);
error = H.showCountries(UserChoice, index);
}
System.out.println("Enter the Name of the Country you wish to locate in the Hash Table or Enter -1 to quit: ");
UserChoice = kb.nextLine();
}
}
}
Let us look at showCountries method:
public boolean showCountries(String paramCountry, int where) {
//....
return false;
}
I removed every line, that does not contain a return statement. As you can see, you always return false no matter if the searched element was found or not.
Therefore this loop:
while (error == false) {
//...
}
is like an infinite loop.
Change the code in your showCountries method to return true, it the country was found.
And consider changing the variable name error to something else. error == false sounds like "everything was ok", but this is not the case here.
If I understand your code correctly, you can change this:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
break;
}
to:
else if (paramCountry.equals(HashTable[location].substring(0,length))) {
System.out.println("The Hash Table Index is " + location + " " + HashTable[location]);
return true;
}
Edit:
Another error-prone point is right here:
int length = paramCountry.length()-1;
while (!(paramCountry.equals(HashTable[location].substring(0,length)))) {
//...
You're cutting off the last character due to the usage of -1.
A small example:
paramCountry = "Eng";
HashTable[0] = "England";
int length = paramCountry.length()-1; // 2 (paramCountry.length() is 3)
And this are the results with the above values:
HashTable[0].substring(0,length)) // "En"
paramCountry.equals(HashTable[0].substring(0, length)) // "Eng".equals("En") -> false
So, you can remove that -1 or get rid of that substring and use contains instead.
Edit 2:
So, after your edit use contains instead of substring you only have one error left (the last one I cuurently see ):
while (!(HashTable[location].substring(0, length).contains(paramCountry))) {
// ...
}
return false;
Before you're calling the method showCountries you're calculating the possible position by calling H.toASCII(UserChoice);. This position is given to the method as location there it is used in the above while loop. This loop will be skipped, because the search country is already found. The bad thing is: you will return false in this case.
Now I suggest to change this return to return true; because this line will only be reached if the searched country was already found (and the while loop was skipped). If the country could not be found, you will return false in this if body: if (location==300||HashTable[location]==null).
I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement