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);
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.
Homework assignment Suggestions only please as I wish very much to learn this as second nature!
The goal is to create an array with a user specified question amount (array size) followed by an answer key (said array size now filled). Then to have the user input the "students" answers to check against key.
I wrote all that no worries. Works lovely. The issue I am having is in two areas:
Create a loop that asks to grade another quiz.
Have it only check/score/calculate every other answer. ie: even answers only.
I have used a do/while loop to continue checking but couldn't get a sentinel value to stick. Also depending on where I placed it, the answers kept coming up as the first check. So I am unsure as to where to place and how to write it. I even tried to use a for loop boxing in the array and student answer portion to no avail.
As regards to having it check every other one, I thought of modifying the count of "i" to something like ((i+1)*2) instead of i++ for the two for loops but I just get errors as that seems to not be proper at all.
Thank you in advance!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main(String[] args) {
int quizQuest = 0, count = 0;
double percentTotal = 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("How many questions are in the quiz? Or enter 0 to quit. ");
quizQuest = scan.nextInt();
int[] answers = new int[quizQuest]; // scan in question total and apply
// to array
System.out.println("Enter the answer key: ");
for (int i = 0; i < answers.length; i++) {
answers[i] = scan.nextInt();
}
for (int i = 0; i < answers.length; i++) {
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if (toGrade == answers[i]) {
count++;
}
}
percentTotal = ((double) count / quizQuest);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println("The questions answered correctly total: " + count);
System.out.println("The percentage correct is: " + defaultFormat.format(percentTotal));
System.out.println("\nAnother quiz to be graded?");
}
}
// do ( quizQuest != 0){ //condition check to run new quiz against KEY
// for (int j = 0; (quizQuest = scan.nextInt()) != 0; j++); {
At the bottom is what I had considered for the loop portion I am having trouble with.
As you asked for hints (and not the code), here it is:
For more than one quizzes, use do-while, as follows:
do{
//do something
//scan the value of quiz quest
//do something
}while(quizquest != 0)
Now, if only answers at even positions are to be checked, do following:
for (int i =0; i <answers.length; i++)
{
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if(i % 2 == 0 && toGrade == answers[i]){
count++ ;
}
}
Create a loop that asks to grade another quiz: You could use a do-while loop with a boolean indicating if the user (teacher?) wants to grade another quiz:
do{
boolean continue = false;
// check if the user wants to continue
while(continue);
Have it only check/score/calculate every other answer. ie: even answers only: You can check for even answers with the modulo operator:
if(i % 2 == 0){
// even answer
}
Hope this helps!
You should have a variable, perhaps named continue, whose default value is 'Y'. At the very beginning, create a while loop that checks the condition continue==Y, and at the end when you ask "Another quiz to be graded?", read in the input to the variable continue.
This is for a class. I'm having trouble figuring out how to best compare the user input with the array answerkey and consequently grade the answers given. I tried searching for a while but wasn't able to find what I needed, so any pointers would be much appreciated!
The prompt for the exercise is:
Write a DMV program that grades the written portion of the driver's license exam. It should have 20 multiple choice questions. It should ask the user to enter the student’s answers for each of the 20 questions, which should be stored in another array. After the student’s answer have been entered, the program should display a message indicating whether the student passed or failed the exam.( A student must correctly answer 15 of the 20 questions to pas the exam). It should then display the total number of correctly answered questions, and the total number of incorrectly answered questions. Input validation: Only accept the letters A, B, C or D.
My code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] answerkey = {"b","d","a","a","c","a","a","d","b","b","b","d","c","a","c","c","a","d","a","a"};
int n = 0;
int correct = 0;
int incorrect = 0;
String answer = "";
for (int i = 0; i < 20; i++){
System.out.println("Please enter your answers. Acceptable input is limited to A,B,C and D.\n");
answer = input.next();
if (answer.compareTo(answerkey[0])==0){
correct++;}
else {incorrect++;}
}
if (correct > 14){
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
System.out.println("You have " + correct + " correct answers.");
System.out.println("You have " + incorrect + " incorrect answers.");
}
Use a dynamic index accessing variable. Right now, every answer you have will be compared to the first answer ("b")
An example of this would be
String[] myArray = { //initialize values here
};
for (int index = 0; index <= myArray.length-1; index++){
if (answer.equals(myArray[index]){
correct++;}
else{
incorrect++;}
}
Try this code on comparing the user input with the array myArray.
Hope this helps.
String[] myArray= { //initialize values here
};
if ((myArray[0]).equals(answer)){
correct++;
} else{
incorrect++;
}
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);
}
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;
}
}