Finding the total value for elements in a String [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My challenge is to find the total value of the elements within a string with user input.
Input by user should be as follows: 1,2,3,4,5,6,7...
I am running into issues when I tried to use StringTokenizer so I went with the split() method but the total amount is off by 7 or by 28 depending on whether I use (i + i) or (+=i) in second for loop.
// Libraries
import java.util.Scanner;
import java.util.StringTokenizer;
public class Project_09_8
{
public static void main(String[] args)
{
// Create instance of Scanner class
Scanner kb = new Scanner(System.in);
// Variables
String input; // Holds user input
String [] result; // Holds input tokens in an array
int i = 0; // Counter for loop control
// User input
System.out.print("Please enter a positive whole number, separated by commas: ");
input = kb.nextLine();
result = input.split(",");
// Converts input String Array to Int Array
int [] numbers = new int [result.length];
// Loop through input to obtain each substring
for (String str: result) {
numbers[i] = Integer.parseInt(str);
i++;
}
// Receive this output when printing to console after above for loop [I#10ad1355.
/*
// Loop to determine total of int array
int sum = 0; // Loop control variable
for (int j : numbers) {
sum += i;
//sum = i + i;
}
// Print output to screen
System.out.println("\nThe total for the numbers you entered is: " + sum);
*/
} // End main method
} // End class

In Java 8 , you can put yourself out of misery
Code:
String s = "1,2,3,4,5,6,7";
String[] sp = s.split(",");
//Stream class accept array like Stream.of(array)
// convert all String elements to integer type by using map
// add all elements to derive summation by using reduce
int sum = Stream.of(sp)
.map( i -> Integer.parseInt(i))
.reduce(0, (a,b) -> a+b);
System.out.println(sum);
output:
28

Since you are already using Scanner you can use the useDelimiter method to split on commas for you.
Scanner also has a nextInt() to do the parsing /converting from String to int for you
Scanner s = new Scanner(System.in)
.useDelimiter("\\s*,\\s*");
int sum = 0;
while(s.hasNextInt()){
sum += s.nextInt();
}
System.out.println(sum);

I suggest you split on (optional) whitespace with \\s*,\\s*, declare variables when you need them and add the sum in one loop (without converting to an int[] copy) like,
public static void main(String[] args) {
// Create instance of Scanner class
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a positive whole number, "
+ "separated by commas: ");
String input = kb.nextLine();
String[] result = input.split("\\s*,\\s*");
int sum = 0;
for (String str : result) {
sum += Integer.parseInt(str);
}
System.out.println(Arrays.toString(result));
System.out.printf("The sum is %d.%n", sum);
}

Related

Calculating Average, A String Tokenization Exercise

I've been trying to get this program working for 3 days now. I've been researching on various websites and stackoverflow as well and I am just not having much success.
The goal is this program is to take in a user input that may be seperated by any amount of white space and also a single semicolon. The integers will then be added and the average will be calculated. The trick is however fractions may also be implemented and can be in the following formats : 12/33 or (12/33).
Fractions are percentage scores out of 100.
I was successfully able to eliminate whitespace and the semicolons I am just unsure how I can do the calculation aspect of this code specially dealing with the fractions.
This is my current code:
public static void main(String[] args) {
System.out.println("Enter a Set of Grades:");
Scanner messageIn = new Scanner(System.in);
String store = new String();
store = messageIn.nextLine();
store = store.trim().replaceAll(" +", "");
//store = store.trim().replaceAll("(", "");
//store = store.trim().replaceAll(")", "");
String[] dataSet = store.split(";");
//messageIn.close();
for (int i = 0; i<dataSet.length; i++) {
System.out.println(dataSet[i]);
}
}
Thank you so much for any help
I haven't gotten this far but for example this code be my input:
98;37; 12/33; (33/90); 88; 120/150;
The output would be:
The Average is: 62.67
How about something like this where you check if the individual grade contains a / and deal with that case separately:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
//Initialize scanner object
Scanner scanner = new Scanner(System.in);
//Prompt user for input
System.out.print("Enter a Set of Grades:");
String store = scanner.nextLine();
//Remove all white space and round brackets
store = store.replaceAll("[\\(\\)\\s+]","");
//Split input into individual grades
String[] grades = store.split(";");
double sum = 0;
//Loop over each entered grade and add to sum variable
for (String grade : grades) {
if(grade.contains("/")) {
double numerator = Double.parseDouble(grade.split("/")[0]);
double denominator = Double.parseDouble(grade.split("/")[1]);
sum += numerator/denominator * 100;
} else {
sum += Double.parseDouble(grade);
}
}
System.out.printf("The average is: %.2f\n", sum/grades.length);
}
}
Example Usage:
Enter a Set of Grades: 98;37; 12/33; (33/90); 88; 120/150;
The average is: 62.67
Try it out here!

Calculate an Average from user input of five to ten numbers using Methods

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

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!

Using while loops to print out vaules [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}
Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}
Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}

String cannot be converted to double error java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My code is suppose to read up to 100 string and store the values in an array.
When an empty string is entered it stops reading information from a user.
Then it validates the strings, converts to double numbers and is stored into a separate array.
Then the average of all valid numbers is found.
The only things that are printed are:
1) the number of valid strings entered
2) all valid strings in reverse order they were inputed
and
3) the average of all valid inputs.
I think I have it okay, except when converting the strings into double numbers. I placed that into a try/catch along with everything else after that because otherwise it can't find the valid inputs.
I am getting an error:(48: error: incompatible types: String cannot be converted to double).
I have tried adding an else to my if statement but it doesn't connect the if and else statements. Though when I add the else statement the error goes away and it just tells me the only error is that it cannot find the if for the else.
What can I do?
EDIT: Thank you, it works now. But I don't think I am finding the average correctly. Any suggestions?
import java.util.*;
public class Grades{
public static void main(String args[]){
int arraycount = 0;
final int SIZE = 10;
int validArraycount = 0;
final int ValidArraySize = 10;
int valuesinValidArray = 0;
Scanner reader = new Scanner(System.in);
String initialInput = new String ("");
String [] sArray = new String[SIZE];
double [] ValidArray = new double[ValidArraySize];
double sum = 0;
boolean exit = false;
System.out.println("You may enter up to 100 grades.");
System.out.println("When you are done entering grades, press the enter/return key.");
//Prints to user. Stops if nothing is entered.
while((arraycount < SIZE)&&(exit == false)){
System.out.println("Enter line " + (arraycount+1) + ": ");
initialInput = reader.nextLine();
if (initialInput.length()<1){
exit = true;
}
else{
sArray[arraycount]=initialInput;
arraycount++;
}
}
//convert string to double
try{
double convertedInput = Double.parseDouble(initialInput);
//validate strings entered by user
if(convertedInput >= 0 && convertedInput <=100){
ValidArray[validArraycount] = initialInput;
}
//Prints number of valid values entered
if(ValidArray.length>0){
System.out.println("The number of valid grades entered is " + ValidArray[0]);
}
//for printing array backwards
for (int i = (arraycount-1); i>=0; i--){
System.out.print(ValidArray.length);
}
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);
System.out.println("Average: " + average);
}
catch(NumberFormatException e){
}
}
}
ValidArray[validArraycount] = initialInput;
is probably supposed to be
ValidArray[validArraycount] = convertedInput;
At this line:
ValidArray[validArraycount] = initialInput;
You are trying to assign a String to an array of doubles. This is where the error is coming. You can try calling double.parseDouble(initialInput) on this if you are sure it will be a double in String form.
It looks like you're assigning the wrong value to your array. Replace:
ValidArray[validArraycount] = initialInput;
With:
ValidArray[validArraycount] = convertedInput;
As previously mentioned, to fix your String conversion issue, you're assignment line should be:
ValidArray[validArraycount] = convertedInput;
To fix your average problem, your code should look like this:
//calculates sum of all values in array of ValidArray (of grades)
for(double d : ValidArray){
sum += d; // <-------- changed from sum += sum;
}
//avergae of valid number array
double average = (sum/ValidArray.length);

Categories

Resources