i'm kind of stuck on this issue. I'm trying to store 1 or more words in a single string, find the length of all the words combined then divide it by the number of words to find the average. I'm required to do this in a while loop (that's the objective of the homework)
When I enter "Hello my name is" it returns the length as
Result:
5
2
4
2
But what I want is to add those results then divide it by the amount of words
5+2+4+2 = 13
13/4 = 3.25
This is what I have so far:
Scanner in = new Scanner(System.in);
int counter = 0;
double sum = 0;
while (in.hasNext()) {
String word = in.next();
double totalchar = word.length();
sum = totalchar + sum;
counter++;
double average = 0;
if (counter > 0) {
average = sum / counter;
}
System.out.println(average);
}
Just move the average calculation and printing outside the while loop:
while (in.hasNext()) {
String word = in.next();
if (word.equals("exit")) {
break;
}
double totalchar = word.length();
sum = totalchar + sum;
counter++;
}
double average = 0;
if (counter > 0) {
average = sum / counter;
}
System.out.println(average);
Maybe this helps you:
You have to move the calculation from average outside the while loop
or it would be calculated and printed every time!
I also improved it a little bit. (you dont need double every time)
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
while (in.hasNext())
{
sum += in.next().length();
counter++;
}
double average = 0.0;
if (counter > 0)
average = sum / counter;
System.out.println(average);
Following example is using BufferedReader:
import java.util.*;
import java.io.*;
class WordAmount {
public static void main(String... args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while((line=br.readLine())!=null) {
if(line.length() > 0) {
String[] words = line.split(" ");
int totalWords = words.length;
int totalChars = 0;
System.out.println("Number of words: "+totalWords);
for(int i=0;i<words.length;i++) {
System.out.println("Length 0f "+words[i]+" : "+words[i].length());
totalChars += words[i].length();
}
System.out.println("Average count :"+ ((double)totalChars/totalWords));
}
}
}
}
Please see below for an enhanced version of that :
int counter = 0;
int sum = 0; // not yet needed to be of type double
String word = null;
while (in.hasNext()) {
word = in.next();
sum += word.length();
counter++;
}
double average = 0;
if (counter > 0) {
average = sum / counter;
}
System.out.println(average);
Please declare variables outside when they will be re-assigned in a loop.
It is not good to put your checking on counter inside the loop because you will be creating average over and over again as well as checking the counter if it's 0.
With that, it slows down your processing turnaround time.
Related
I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)
I have a class assignment where we have to use Math.random to generate values of 0 or 1 representing heads and tails respectively. The point of the program is to have the user input the number of times the coin is flipped, and the program then spits out a string of random 0s and 1s representing the flips. The program then has to find and state the longest number of heads in a row.
eg.
(heads = 0 / tails = 1)
number of tosses: 10
result: 0001100100
longest sequence of heads: 3
this is what I have so far:
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip
{
public static void main(String args[])
{
int Toss; // State variable for tosses
int Heads; // State variable for # of heads
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
for(int i = 0; i < Toss ; i++)
{
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
}
System.out.println("");
System.out.println("Longest sequence of heads is "); // Says largest sequence of heads
}
}
I'm stuck as to how I read the sequence and then display the longest consecutive head count.
I have written a function to do this. I take the String that you were printing and made a String out of it. I pass this string as a parameter to the function and count the consecutive 0 in it.
This is the code for the same:
import java.util.Scanner;
public class CoinFlip {
public static void main(String args[]) {
int Toss; // State variable for tosses
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
StringBuffer coinSequenceBuffer = new StringBuffer(Toss);
for (int i = 0; i < Toss; i++) {
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
coinSequenceBuffer.append(Coin);
}
String coinSequence = coinSequenceBuffer.toString();
System.out.println("");
int numberOfConsecutiveHead = findNumberOfConsecutiveHead(coinSequence);
System.out.println("Longest sequence of heads is " + numberOfConsecutiveHead);
}
private static int findNumberOfConsecutiveHead(String coinSequence) {
int count = 1;
int max = 0;
// Starting loop from 1 since we want to compare it with the char at index 0
for (int i = 1; i < coinSequence.length(); i++) {
if (coinSequence.charAt(i) == '1') {
// Since we are not intersted in counting 1's as per the question
continue;
}
if (coinSequence.charAt(i) == coinSequence.charAt(i - 1)) {
count++;
} else {
if (count > max) { // Record current run length, is it the maximum?
max = count;
}
count = 1; // Reset the count
}
}
if (count > max) {
max = count;
}
return max;
}
}
I have tried adding comments so that you can easily understand it. Let me know if you face any issue in understanding it.
This is pretty simple. Just count zeros and reset counter when not zero.
public static void main(String... args) {
System.out.print("Enter number of tosses: ");
int[] arr = new int[new Scanner(System.in).nextInt()];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(2);
System.out.println(Arrays.toString(arr));
System.out.println("Longest sequence of heads is " + findLongestZeroSequence(arr));
}
public static int findLongestZeroSequence(int... arr) {
int res = 0;
for (int i = 0, cur = 0; i < arr.length; i++) {
if (arr[i] == 0)
res = Math.max(res, ++cur);
else
cur = 0;
}
return res;
}
Here's my go at it:
class CoinFlip {
public static void main(String args[])
{
// Get number of tosses from user
System.out.print("Enter number of tosses: ");
System.out.flush();
Scanner input1 = new Scanner(System.in);
int toss = input1.nextInt();
// Build a string of random '0's and '1's of the specified length (number of tosses)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < toss ; i++)
{
long coin = Math.round(Math.random());
sb.append(coin == 0? '0' : '1');
}
String seq = sb.toString();
// Print the generated String
System.out.println(seq);
// Walk through the string tallying up runs of heads
int count = 0;
int max = 0;
for (int i = 0 ; i < seq.length() ; i++) {
if (seq.charAt(i) == '0') {
count += 1;
} else {
if (count > max)
max = count;
count = 0;
}
}
// Gotta check at the end to see if the longest sequence of heads
// was at the end of the string
if (count > max)
max = count;
// Print the length of the longest sequence
System.out.println("Longest sequence of heads is " + max);
}
}
Sample run:
Enter number of tosses: 40
1000001000000010010101011000011100001000
Longest sequence of heads is 7
Explanations after the code.
import java.util.Scanner;
public class CoinFlip {
private static final int HEADS = 0;
private static final int TAILS = 1;
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.print("Enter number of tosses: ");
int toss = input1.nextInt();
int count = 0;
int longest = 0;
StringBuilder sb = new StringBuilder(toss);
for (int i = 0; i < toss; i++) {
int coin = (int) ((Math.random() * 10) % 2);
sb.append(coin);
System.out.printf("Got %d [%s]%n", coin, (coin == HEADS ? "HEADS" : "TAILS"));
if (coin == HEADS) {
count++;
System.out.println("count = " + count);
}
else {
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
count = 0;
}
}
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
System.out.println(sb);
System.out.print("Longest sequence of heads is " + longest);
}
}
In order to generate a random number which must be either 0 (zero) or 1 (one), I call method random() of class java.lang.Math. The method returns a double between 0.0 and 1.0. Multiplying by ten and then performing modulo 2 operation on that number returns either 0.0 or 1.0 which is a double and therefore needs to be cast to an int.
Each time the above calculation returns 0 (zero) I increment a count. If the calculation returns 1 (one) then I check whether the count is greater than longest and update longest accordingly, after which I reset the count back to zero.
Note that if the last toss is "heads" then the check for the longest sequence will not be performed. Hence I repeat the check for the longest sequence after the for loop.
At the end of the for loop, I have all the required information, i.e. the string that records all the results of all the coin tosses plus the longest sequence of heads.
Here is sample output:
Enter number of tosses: 10
Got 1 [TAILS]
Got 1 [TAILS]
Got 1 [TAILS]
Got 0 [HEADS]
count = 1
Got 1 [TAILS]
longest = 1
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
Got 1 [TAILS]
longest = 2
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
1110100100
Longest sequence of heads is 2
For a homework assignment i need to take an unspecified number of grades( no more than 100), get the average, and display how many are above and below average. I'm trying to use a Sentinal value to exit the loop when putting in grades. And while it does exit the loop, it also takes the Sentinal value as a grade input and calculates that into the average. For example if I enter scores "50 75 100" then exit with -1. the results will display something like 74.66666666667. I can sort of see why it is doing this looking at my for loop but I'm struggling to find a way to fix it.
public class AnalyzeScores {
public static void main(String[] args) {
double scores, average;
int aboveAvg, belowAvg;
double sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
double[] scoresList = new double[100];
for (int i = 0; i < 100; i++) {
System.out.print("Enter Score " + (i + 1) + "(negative score exits): ");
scoresList[i] = input.nextDouble();
sum = sum + scoresList[i];
count++;
if (scoresList[i] < 0) {
average = (sum / i);
System.out.println("average is " + average);
return;
}
}
}
}
you should move this piece of code:
sum = sum + scoresList[i];
count++;
from before the if condition to after the if condition.
That's because you put -1 to your list while calculating the average. You need to check if the input value is below zero before adding it to scoresList.
Here is the code where this problem is fixed (but it still requires some improvements):
public class Main {
public static void main(String[] args) {
double scores, average;
int aboveAvg, belowAvg;
double sum = 0;
int count = 0;
Scanner input = new Scanner(System.in);
double[] scoresList = new double[100];
for (int i = 0; i < 100; i++) {
System.out.print("Enter Score " + (i + 1) + "(negative score exits): ");
double score = input.nextDouble();
if (score >= 0) {
scoresList[i] = score;
sum = sum + scoresList[i];
count++;
}
else break;
}
average = (sum / count);
System.out.println("average is " + average);
}
}
I've just recently started programming Java and I'm having a problem that's making me want to break things. It starting to get annoying, and I'm feeling pretty stupid right now.
The task is to write a program that asks for five numbers to be input into an array (yes, can't use a list) and to then calculate the average of the five numbers input.
Where am I going wrong?
My current code calculates the average after each input. I want to do that after they've all been inserted, otherwise what is the point?
All help is greatly appreciated, you believe me!
Here's the code:
import java.util.Scanner;
public class Uppg3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
double average = sum / 5;
System.out.println("Average is " + average);
input.close();
}
}
You ought to encapsulate such a thing in a method.
You can either process all the numbers at once by storing them in an array and passing them at the same time or keep a running tally and return it on request.
public class StatisticsUtils {
private double sum;
private int numValues;
public StatisticsUtils() {
this.sum = 0.0;
this.numValues = 0;
}
public void addValue(double value) {
this.sum += value;
++this.numValues;
}
public double getAverage() {
double average = 0.0;
if (this.numValues > 0) {
average = this.sum/this.numValues;
}
return average;
}
public static double getAverage(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Looking at this for loop
for (int i = 0; i < numbers.length; i++)
{
System.out.println("enter a number: ");
numbers[i] = input.nextInt();
sum = numbers[i];
}
You are adding it to the array just fine, but you keep setting the sum to whatever they enter. For example, if I enter 5 3 2, the array will have 5 3 2 in it, but the sum will be set to 2. If I only entered 5 3, it would be set to 3.
One solution would be to use +=, that way it adds that number to whatever the current value is (which you start at 0). It's also important to note that when you divide two integers (sum and 5), it will not give you a decimal. This can be solved by using 5.0 or casting sum to a double.
Your code is currently just assigning a different value to sum on every iteration of the loop. You need to change sum = numbers[i]; to sum += numbers[i]; (equivalent to sum = sum + numbers[i];). You'll also want to change int sum = 0; to double sum = 0 so that your answer has decimals.
Ok, it works with the "+=", love you Chris Phelps. That and changing:
int sum = 0;
to
double sum = 0;
To make the answer have a decimal. Thanks a lot you guys! A weight has been lifted of my chest :).
Code for calculating average of array input
package com.imedxs;
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("for calculating average of array");
int n=0;
int b=sc.nextInt();
int[] numbers = new int[b];
int sum = 0;
for (int i = 0; i < b; i++)
{
System.out.println("enter a number: ");
numbers[i] = sc.nextInt();
sum += numbers[i];
n++;
}
double average = sum / n;
System.out.println("Average is " + average);
}
}
My original code is:
import javax.swing.JOptionPane;
public class average {
public static void main(String[] args) {
String str1;
String str2;
String str3;
int numbersToAverage;
str1 = JOptionPane.showInputDialog("Please enter the amount of numbers you would like to average: ");
numbersToAverage = Integer.parseInt(str1);
// while statement will provide error message so user cannot enter 0
while (numbersToAverage < 1) {
str3 = JOptionPane.showInputDialog("Invalid entry: Please enter one or more numbers to average: ");
numbersToAverage = Integer.parseInt(str3);
}
// array size is set to equal user input
double[] numbers = new double[numbersToAverage];
double sum = 0;
for (int i = 0; i < numbersToAverage; i++) {
str2 = JOptionPane.showInputDialog("Enter number " + (i + 1)
numbers[i] = Double.parseDouble(str2);
// the sum equals numbers in the array added together
sum += numbers[i];
}
// Calculates the average of the numbers entered by the user
double average = sum / numbersToAverage;
// Prints in a dialogue box to user the average
JOptionPane.showMessageDialog(null, "The average of the numbers you entered is: " + average);
}
}
and I am now having to calculate the average in a separate method and I am having a hard time figuring out how to do that? So far I have:
import javax.swing.JOptionPane;
public class average {
public static void main(String[] args) {
String str1;
String str2;
String str3;
int numbersToAverage;
str1 = JOptionPane
.showInputDialog("Please enter the amount of numbers you would like to average: ");
numbersToAverage = Integer.parseInt(str1);
// while statement will provide error message so user cannot enter 0
while (numbersToAverage < 1) {
str3 = JOptionPane
.showInputDialog("Invalid entry: Please enter one or more numbers to average: ");
numbersToAverage = Integer.parseInt(str3);
}
// array size is set to equal user input
double[] numbers = new double[numbersToAverage];
//double sum = 0;
for (int i = 0; i < numbersToAverage; i++) {
str2 = JOptionPane.showInputDialog("Enter number " + (i + 1)
numbers[i] = Double.parseDouble(str2);
JOptionPane.showMessageDialog(null, "The average of the numbers you entered is: " );
}
}
public static double average(double[] array){
double sum;
sum += array[i];
double average = sum / array.length;
return average;
}
}
I am having a hard time figuring out how to call this in the main method and how to get the correct calculation. What is the best way to do this? Do I need a for loop in the average method or should I keep it in the main?
Just do this:
StatUtils.mean(array);
you can find more about StatUtils here.
In Java 8 one might use Streams:
final double avg = array.length > 0 ? DoubleStream.of(array).sum() / array.length : 0;
Or in an own function:
public static double average(final double[] array) {
return array.length > 0 ? DoubleStream.of(array).sum() / array.length : 0;
}
Yes you need a loop, try to do something like this:
public static double average(double[] array) {
if(array.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = sum / array.length;
return average;
}