Finding the average of certain numbers out of a text file - java

Here is my code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class QuestionTwo
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
double average;
double numbertocheck;
int length;
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
length = reader.nextInt();
//Here is where I would put the statement that says "File is not found, enter the filename again"
System.out.println("The number to check: ");
numbertocheck = keyboard.nextDouble();
if (length > numbertocheck)
{
//here is where I would put the average calculation
System.out.println("The average of the numbers that are greater than" + numbertocheck + "is " /**+ average*/);
}
}
}
with the text file looking as such:
30
44
23
56
43
2
32
35
90
12
My output comes out to nothing; it simply asks the two questions and draws a blank (even before I made a bunch of things into comments). This code is attempting to answer the question:
"Write a program that asks the user to enter the name of a file that contains a set of integer values, and then asks the user to enter an integer number.
The program should display the average of the numbers
that are greater than the input number. Use Notepad or another text editor to create a simple file that can be used to test the program.
First, the user enters the file name as below:
Enter the file name: input.txt
and if, for example, the file ‘input.txt’ contains the following numbers:
30
44
23
56
43
2
32
35
90
12
and then, if the user enters an integer number, as:
The number to check: 40
the program should display the output as:
The average of the numbers that are greater than 40 is 58.25
Note that average of numbers 44, 56, 43 and 90 is 233/4 = 58.25. The average must be shown up to two decimal points.
If the input file is not found, the user must be prompted to enter the filename again with the following message
“File is not found, enter the filename again”.
Which will then prompt the question to be again until a valid file is found."
The problems arise for me when it comes to parsing the text file and finding the average of the numbers greater than the value asked for. That and looping the question asking the user to enter the file name and then repeating that question until a file is found. I have thought of using the Decimal format class, but do not know how to properly utilize it. Any help would be appreciated!

My first comment is you might want to take some lessons. This is pretty basic stuff.
But to answer your question, use a while loop, with an if/else statement inside, to get proper input.
For your next problem, you probably want to use .nextLine instead of .next, because some file names have spaces in them.
Third problem, use a for loop to check each integer one at a time, and compare it to the range needed. Then use if/if else statements/switch statements and an array to store the values, and after all values are checked, do the math on the content of the array.
Again, i highly recommended taking some basic java lessons.

Related

How to write a random group generator in java using else-if statements?

I have to code a program that allows the user to choose between two task: a random group generator, and a task that parses and counts an input sentence by word. I am really confused on how to go about it.
The instructions are:
Team Maker:
If 1 is entered, the application prompts the user to enter the desired number of teams to make.
If 0 is entered, nothing happens and the application continues on prompting the user to enter 1 or 2. See Fig-3.
If the number of teams is 1 or greater, the application displays the team number, beginning from 1, followed by three full names randomly selected from the 49 students provided in COP2510.txt. See also Fig-3, where 1 and 3 are entered for making one team and three teams, respectively. Hint: Use the Random class as seen in GetRandom1.java or GR.zip of Quiz 3 to implement this random selection.
All names of each team must be displayed beginning with a 'tab'.
It's very important in this application that no student appears in the same or different teams more than once.
Hint: there are more than one way to "map" a random number (integer) to a specific student name. Using if....else if....else if....else if.... is one possible approach and is recommended here. Storing all names in an array is another way but is not introduced until Chapter 10 .
Counting Words:
If 2 is entered, the application prompts the user to enter one or more sentences. See Fig-4.
The application uses the space character, " ", to separate and count words in the input. If there are two or more consecutive spaces, they are treated as just one. That is, "AA BB" and "AA BB" both contains two words. See Fig-5.
All leading and trailing spaces in the input would be ignored. Hint: use 'trim()' method of String.
The application display two lines of dashes, i.e., "-------------------" to enclose every word it finds. Each word must be displayed together with its length. For example, if "Hi, John!" is entered, the two lines between dashes should be "Hi, (3)" and "John!(5)".
After the 2nd dashes line, the total number of words is displayed to end the task.
If no words or sentences are entered, a message of "Nothing or only space(s) is entered." is displayed between the two dashes lines and the count is zero. See the last input in Fig-5.
Hint: You may use trim(), indexOf(), length(), substring(), and equals() methods of String to implement the above word count task. Even the same methods are used, there are different approaches to get this task completed.
I got the first part where the program welcomes the user, and shows what the program does. However I don't know how to code the random team generator. I can only use else if statements. Someone told me to assign a random number to each name and then use the else if statements, however I have no idea how to do that. And as for the word counter I just have no clue. If anyone could help that would be great.
import java.util.Scanner;
import java.util.Random;
public class asssignment3 {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
//print out a task prompt
System.out.println("Assignment-3 can perform the following two task:");
System.out.println();
System.out.println("\t1-Making 3-member tems from class of COP2510");
System.out.println("\t2-Parsing and counting an input sentence by word");
System.out.println();
System.out.print("Enter 1 or 2 to begin your task or anything else to quit: ");
String choiceNumber = sc.nextLine ();
if (choiceNumber.equalsIgnoreCase("0")) {
System.out.println("Enter 1 or 2 to begin your task or anything else to quit: ");
String optionNumber = sc.nextLine ();
}
Random r = new Random();
if (choiceNumber.equalsIgnoreCase ("1")) {
String studentName = "";`
Personally, I would forego the if-else and do the array. Make an array with every integer from 0-N, where N is the number of the students. Then, shuffle the list around. I believe Java has a prebuilt function for it, but if not the algorithm for one is trivial.
From there, simply read in the student file line by line and assign the corresponding number from the shuffled array.
Example psuedocode:
# >>> Generate the list of numbers of shuffle it. <<< #
N = number of students
numbers = [i for i in range(N)]
random.shuffle(numbers)
# >>> Initialize a list to store number-student pair <<< #
students = []
# >>> Read in the student file line by line <<< #
for line in students.txt:
randomNumber = numbers.pop()
students.append((line, randomNumber))
Viola, the students list now has all of the students, paired with a random number.
As for counting words, run the input through trim() and then split().
# >>> Removes whitespace before and after the string (" A " -> "A") <<< #
input = input.trim()
# >>> Splits input into an array ("AA BB CC" -> ["AA", "BB", "CC"]) <<< #
words = input.split(" ")
numWords = word.length

Substring of Scanner Input

How do I get a substring from scanner input?
(Before you comment saying "duplicate" or "look it up", I have. I haven't gotten any answers that apply or are within the range of what I'm currently allowed to utilize in my programming course.)
I'm trying to get the program to accept user input using the scanner class, and then print out a part of the input, but only the tail end. In this example I have the scanner asking for a debit card number and want the input to be printed back as "**** **** **** nnnn" (nnnn being numbers from the scanner input). Here's what I have:
import java.util.Scanner;
public class CyberlifePurchase
{
public static void main(String[ ] args)
{
Scanner payment = new Scanner(System.in);
System.out.println("Please enter your debit card number: ");
String cardNumber = in.next();
System.out.println();
String concealedCardNumber = cardNumber.substring(15);
System.out.println("Card Number: " + "**** **** **** " + concealedCardNumber);
When I compile everything there are no compile errors, but when I run the program this is what I get after entering a card number (in nnnn nnnn nnnn nnnn format):
java.lang.StringIndexOutOfBoundsException: String index out of range: -11
You should use in.nextLine() rather than in.next()
next method in the Scanner class uses space as a token and only returns the data before the space, hence you can use nextLine method
As already mentioned, use scanner.nextLine() instead of scanner.next().
If you want the last part of the string, it is safer to use something like:
originalString.substring(originalString.length()-4);
Replace 4 with the actual character count you want to output. It would be also wise to check that the length of the original string is more that the amount you substract (4 in the example above).
Besides fixing your code, if you want to impress your teacher you should add some error checking as well. This can double as a safeguard against StringIndexOutOfBoundsException. For example, replace the last two lines of codes with this:
if (cardNumber.length() < 19) {
System.out.println("c'mon... its like this!! \"nnnn nnnn nnnn nnnn\"");
} else {
String concealedCardNumber = cardNumber.substring(15);
System.out.println("Card Number: " + "**** **** **** " + concealedCardNumber);
}

JAVA - Program functions as input output, input output; want to make it so program functions as input input, output, output, respectively

I've just started learning Java, and I wanted to overcome a hurdle that showed up when trying to create a Java program for this 'problem'. This is the problem I had to create a program for:
Tandy loves giving out candies, but only has n candies. For the ith person she gives a candy to, she gives i candies to that person. For example, she first gives Randy 1 candy, then gives Pandy 2 candies, then Sandy 3. Given n, how many people can she give candies to?
Input Format
The first line is an integer x, denoting the number of test cases.
The next x lines will contain a single positive integer, n.
SAMPLE INPUT
2
1
5
Output Format
x lines, with each line containing a single integer denoting the number of people Tandy can give candies to.
SAMPLE OUTPUT
1
2
To solve this problem, I created a program, and it functions well, but it doesn't match what the problem is asking for.
The code:
import java.util.Scanner;
public class PRB1CandyGame {
public static void main(String[] args)
{
Scanner cases = new Scanner(System.in);
int repeats = cases.nextInt();
while (repeats > 0)
{
int x = cases.nextInt();
int i = 1;
for(i = 1; x-i>=0; i++)
{
x = x-i;
}
System.out.println(i-1);
repeats--;
}
}
}
(Sorry if the code is messy!)
My code takes in the number of 'cases' and then that's how many times I can enter in a number of candies to get the number of people it can provide. However, my program takes the number of candies and then outputs the number of people right after, while I want it to take in all the inputs (number of inputs is based on what the user enters for the number of cases), and then output all the values, rather than what I have. If you can explain to me how I can do that, it will help a lot.
Thanks!
From my understanding, you want your input to be stored some where first before you start processing answers then output all answers at once.
I Honestly think the question wants you to process each test case as input then output the result. So you're presently on the right track.
But if you want to get all inputs then process each one then output, use an array since you know the size of the test case. You will also need to create an array of same size for output then process each ith item in the input array and store each result in the same ith position in the output array.
Hope this helps

Java Looping for user input error until it's an int/double and distinguishing between the error input

I have a problem I sort of half fixed? It's more of a logic error, I think. My program overall is running smoothly, but I need to fix the flow of how my program interprets user input.
This program should report user error if they input a non numerical value or a negative number. And if the user enters 0, then is should accept it as a correct answer ( I have yet to figure out how to do that since my condition is whether or not it's a double).
I'm trying to differentiate between whether the user inputs a negative number or a character in the feedback. So far, I've made a loop to continuously prompt the user to enter a number if they don't input a double. Though I'm not sure how to go about accepting a 0 as an answer and filtering out negative numbers. I went back to my flow diagram and figured I may need to use an if-else statement to do this. But how can I do that while keeping the loop going? I'm not totally sure how I'm suppose to format that kind of thing.
Help is appreciated for this newbie! Thank you!
while(looping){
// Prompt user to enter how many grades they want averaged
System.out.println("How many grades would you like to average? ");
// Check if the input variables are positive numerical variables
// Or else report to user to input a number
while(!input.hasNextDouble()) //cannot be negative
{
input.next();
System.out.println("Please enter a number: ");
}
gradeNumber = input.nextInt();
// Prompt user to enter the grades
System.out.println("Please enter " + gradeNumber + " grades: ");
// Use a for-loop to control how many loops - reference to gradeNumber
for(gradesCount = 0; gradesCount < gradeNumber; gradesCount++){
// Check if the input variables are numerical variables
while (!input.hasNextDouble())
{
input.next();
System.out.println("Please enter a number: ");
}
gradesInput = input.nextDouble();
finalGrades = finalGrades + gradesInput;
} // end loop

Counting unique numbers from int array - Java [duplicate]

This question already has answers here:
counting occurrence of numbers in array
(6 answers)
Closed 8 years ago.
I am trying to build and array where the user enters numbers. Then at the end the program outputs a list of the entered numbers along side the amount of times each individual number was entered.
Currently I have:
package arraypractice;
import java.util.Scanner;
public class Entry {
private Scanner scan = new Scanner(System.in);
public void userInput(){
System.out.println("Please tell me the amount of numbers you will be $ entering: ");
int [] arr = new int[scan.nextInt()];
for(int i=0;i<arr.length; i++) {
scan = new Scanner(System.in);
System.out.println("Please enter a number: ");
while(scan.hasNextInt()){
int x = scan.nextInt();
arr[i]= x;
break;
}
}
for(int i:arr){System.out.println(i + " occurs");
}
}
}
For example this outputs:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
25 occurs
21 occurs
BUILD SUCCESSFUL (total time: 10 seconds)
In a perfect world I would like to output to look like this:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
Number Times Entered
25 occurs 1
21 occurs 1
BUILD SUCCESSFUL (total time: 10 seconds)
I am not sure how to implement this. A second array? If so how? Also is there a way I can get the headings Number and Times Entered?
You are not seeing a main method because it is in another class that instantiates this.
Thanks.
To get a heading you just put a println() method before you run the for loop to print out the array.
It seems like you want to format the print out. To do that you would need to use
printf("%6d%10s%6d", i, "occurs", array[i])
That's the general idea.

Categories