So I know I have to get the remainder in order for this to work. However, it works perfectly except for the first line where it gives me 6 instead of 5 for the first line. I think this is happening because 0 is considered a multiple of 5, but I am not really sure of how to get around this. I looked at How to display 5 multiples per line? but I am having trouble seeing how to fix my code using that as it doesn't appear like they had the first line being messed up issue. For example, if I enter 17 into the positive number it gives 6 numbers for the first line and then 5 for the rest. Then it gives the remaining ones which is what I want. For the average part you can type anything as I am going to work on that later. So the format should be something like this:
4.50, 5.56, 2.73, 8.59, 7.75,
...
5.34, 3.65,
Here is my code and thanks for the help:
import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
ArrayFun a = new ArrayFun();
}
public ArrayFun() {
Scanner input = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive number: ");
int limit = input.nextInt();
// Get input from the user
System.out.print("Enter the lower bound for average: ");
double lowerBound = input.nextDouble();
// Generate an array of random scores
double[] allScores = generateRandomArrayOfScores(limit);
// Display scores, wrapped every 5 numbers with two digit precision
DecimalFormat df = new DecimalFormat("0.00");
displayArrayOfScores(allScores , df);
// Calculate the average of the scores and display it to the screen
//double average = calculateAverage(lowerBound , allScores); //
System.out.print("Average of " + limit + " scores ");
System.out.print("(dropping everything below " + df.format(lowerBound) + ") ");
//System.out.println("is " + df.format(average) );//
}
private double[] generateRandomArrayOfScores(int num) {
double[] scores=new double[num];
for (int i=0;i<scores.length;++i) {
double number=Math.random()*100.0;
scores[i]=number;
}
return scores;
}
private void displayArrayOfScores(double[] scores, DecimalFormat format) {
System.out.println("Scores:");
for (int i=0;i<scores.length;++i) {
String num=format.format(scores[i]);
if ((i%5==0)&&(i!=0)) {
System.out.println(num+", ");
}
else{
System.out.print(num+", ");
}
}
System.out.println();
}
}
The problem is indeed the 0, exactly this part (i%5==0)&&(i!=0). Replace this by i%5==4 and it should work. It is because System.out.println(...) makes the new line after printing the string and if you count 0,1,2,3,4,5 those are 6 numbers, because you treat 0 differently. The last number in the groups of 5 has a modulo of 4. (i+1)%5==0 would work too fo course, it is the equivalent. Alternatively you could do an empty System.out.println() using your condition and print the number as the others afterwards.
Related
I need to create a program that will calculate an average of arrays up to 10 numbers. Here are the requirements:
The program uses methods to:
1.Get the numbers entered by the user
2.Calculate the average of the numbers entered by the user
3.Print the results
The first method should take no arguments and return an array of doubles that the user entered.
The second method should take an array of doubles (the return value of the first method above) as its only argument and return a double (the average).
The third method should take an array of doubles and a (single) double value as arguments but have no return value.
I tried the below, but the biggest problem I'm running into (that I can tell so far at least) is that the program is printing both statements before allowing the user input. I know how to do this normally, but I think I'm getting confused because of the array piece. Thanks much.
public static void main(String[] args) {
double[] userNumbers = printUserNums();
double average = getAverage(userNumbers);
printAverage(average, userNumbers);
}
public static double[] printUserNums() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter five to ten numbers separated by spaces: ");
double[] userNums = new double[10];
return userNums;
}
public static double getAverage(double[] userNums) {
Scanner in = new Scanner(System.in);
int counter = 0;
double average = 0.0;
double sum = 0;
for (int i = 0; i < userNums.length; i++) {
sum = sum + userNums[i];
}
if (counter != 0) {
average = sum / userNums.length;
}
return average;
}
public static void printAverage(double average, double[] userNums) {
System.out.printf("The average of the numbers " + userNums + " is %.2f", average);
}
}
You are never asking for the numbers!
You need to ask for an input from the scanner:
String inputValue = in.next();
and then split your full string (containing the numbers separated by space) using space as your regex to get the numbers:
String[] stringValues = inputValue.split("\\s+");
You should probably have some kind of checking to verify that there is at least 5 values and no more than 10 values by your requirements.
If the checking passes, just loop through your array and convert the string values to double values with Double.valueOf(String s) and store them in your double array.
It's not how I would normally get numbers from user input but if you want to have them in one go, this should work.
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.
It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?
public class AverageWithMethods {
public static void main(String[] args) {
String userNumbers = getUserNums();
double average = userNumAvg(userNumbers);
printAverage(0, userNumbers);
}
public static String getUserNums() {
Scanner in = new Scanner(System.in);
String userNumInput = "";
System.out.print("Please enter five to ten numbers separated by spaces: ");
userNumInput = in.nextLine();
return userNumInput;
}
public static double userNumAvg(String userNumInput) {
Scanner in = new Scanner(System.in);
Scanner line = new Scanner(in.nextLine());
double count = 0;
double average = 0.0;
double sum =0;
while (in.hasNextDouble()) {
count++;
sum = line.nextDouble();
}
if (count != 0) {
average = sum / count;
count = Double.parseDouble(userNumInput);
}
return average;
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);
}
}
count how many spaces there are in your string. You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String
e.g.
String fiveNums = "1 2 3 4 5";
String noSpaces = fiveNums.replace(" ", "");
System.out.println(fiveNums.length() - noSpaces.length());
From your first section of code I am making the assumption all the numbers are entered on a single line all at once.
My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?
The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.
Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
numbers++;
total += line.nextDouble();
}
line.close(); // Good habit
You can then compute your average with all this information:
double avg = total/numbers;
Notes:
Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.
I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.
When you want to understand how many numbers input the user, you can:
String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;
User input quantity numbers.
Here is one of the possible ways to do from your original code:
import java.util.Scanner;
public class GetAverage {
public GetAverage() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter five to ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new GetAverage();
}
}
OUTPUT:
Please enter five to ten numbers separated by spaces:
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50
So my teacher gave me an assignment to do (will be shown below) and I tried to do it but just could not figure it out, here's the assignment:
Consider the following program that allows something like 8 + 33 + 1,345 + 137 to be entered as String input from the keyboard, A Scanner object then uses the plus signs (and any adjoining white space) as delimiters and produces the sum of these numbers (1523).
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
Now modify the program as to allow either plus or minus signs
^^^THAT WAS THE ASSIGNMENT^^^
Here is my source code:
//I can't get it to work if I use subtraction and addition at the same time but they work separately
import java.util.Scanner;
public class AddEmUp {
public static void main(String[] args) {
//Here we create a String
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine();
//Now we convert the String to a scanner because we will be using Scanner methods
Scanner sc = new Scanner(s);
//Creates sum
int sum = 0;
//Does it's magic if it is addition
if (s.contains("+")) {
sc.useDelimiter("\\s*\\+\\s*");
while (sc.hasNextInt()) {
sum = sum + sc.nextInt();
}
}
//Does it's magic if it is subtraction
if (s.contains("-")) {
sc.useDelimiter("\\s*\\-\\s*");
while (sc.hasNextInt()) {
sum = sc.nextInt();
sum = sum - sc.nextInt();
}
}
//Prints the magic
System.out.println("Sum is: " + sum);
}
}
Can anybody help me solve the problem (First comment in my source code)???
I'm going to help you answer this in a way that's (hopefully) consistent with what you've learned so far. Since you haven't learned about arrays yet and are working with a Scanner with a delimiter pattern, we'll have to work around this constraint.
First, for the purposes of a school assignment, we can probably safely assume that your inputs will follow a particular pattern, along the lines of: (number)(operator)(number)(operator)(number)... and so on; additionally, you're probably not worried about input checking (making sure there are no letters/symbols/etc) or negative numbers, so we'll ignore those scenarios. Since you are only dealing with + and -, your delimiters are "\\s*\\+\\s*" and "\\s*\\-\\s*", respectively. Since these values don't change (they are constants), and (in a real program) would be used multiple times in different places, we typically store these in their own final variables:
final String PLUS = "\\s*\\+\\s*"; // by convention, constants in java are named with all caps
final String MINUS = "\\s*\\-\\s*";
Now, let's look at your sample input: 8 + 33 + 1345 - 137. How can you account for mixed operators?
int sum = 0;
Scanner sc = new Scanner(s); // s = "8 + 33 + 1345 - 137"
//What now?
You can still pull this off with one loop, but it will require some intermediate steps.
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137" (!!!)
In the above example, temp would first be "8" (note that it's a String here), then "33" on the next pass, then "1345 - 137" on the third pass. You would typically use Integer.parseInt() to turn a String to an int, like so:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
sum += Integer.parseInt(temp);
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137", code breaks at Integer.parseInt(temp)
However, this code breaks on the third pass, because "1345 - 137" is clearly not an integer value. This is where storing the value in temp comes into play; you can use a nested loop to evaluate subtraction portions of your expression! You were on the right track with checking for + and - in the input, and here is a more appropriate spot to use it:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
// check if there are - signs in temp
if(temp.contains("-")){
// if there are, evaluate the subtraction expression
// for this example, temp = "1345 - 137"
Scanner sc2 = new Scanner(temp);
sc2.useDelimiter(MINUS);
int diff = sc2.nextInt(); // diff = 1345
while(sc2.hasNext()){
diff -= sc2.nextInt(); // diff = 1345 - 137 = 1208
}
sum += diff; // adds the result to the sum
} else {
sum += Integer.parseInt(temp); // there is no - sign, so skip ahead and just add to the sum
}
}
You'll notice I didn't check if the input contains a + sign at the beginning before the loop; this is because I'm assuming that even if you enter something like 1 - 5 - 9, the Scanner will still return at least that whole string when sc.next() is called, which will still go into the inner loop, and the expression will still be evaluated. I haven't used a Scanner in a very long time, so if this assumption is incorrect, you'll have to fix that.
User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}
I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p