Arrays, Doubles, IF/Else - java

Im suppose to write a code using an Array of numbers and apparently not a string and they need to be double. The way I wrote the code, the only way I know how, works. Maybe im making it too complicated and an array would make it simple idk. Im new to programming, new as in a few days. please help.
What is needed is:
Write a code that will average the input of 10 numbers and show the avg along with if they pass or fail. if < 50 fail, else > 50 pass.
we have to use an array, we need to use JOptionPane.showMessageDialog., the numbers need to be double and rounded to two decimals.
I declared double but i get an error if i enter a decimal number. If i just run the code as is, it will let me enter 10 numbers, avg them and then tell me if i pass or fail. Im just lost when it comes to using the other factors. thanks
the working code follows:
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail {
public static void main(String[] args) {
String firstNumber,
secondNumber,
thirdNumber,
fourthNumber,
fifthNumber,
sixthNumber,
seventhNumber,
eighthNumber,
ninethNumber,
tenthNumber;
double number1,
number2,
number3,
number4,
number5,
number6,
number7,
number8,
number9,
number10,
sum;
firstNumber =
JOptionPane.showInputDialog ( "Enter 1st Grade" );
secondNumber =
JOptionPane.showInputDialog ( "Enter 2nd Grade" );
thirdNumber =
JOptionPane.showInputDialog ( "Enter 3rd Grade" );
fourthNumber =
JOptionPane.showInputDialog ( "Enter 4th Grade" );
fifthNumber =
JOptionPane.showInputDialog ( "Enter 5th Grade" );
sixthNumber =
JOptionPane.showInputDialog ( "Enter 6th Grade" );
seventhNumber =
JOptionPane.showInputDialog ( "Enter 7th Grade" );
eighthNumber =
JOptionPane.showInputDialog ( "Enter 8th Grade" );
ninethNumber =
JOptionPane.showInputDialog ( "Enter 9th Grade" );
tenthNumber =
JOptionPane.showInputDialog ( "Enter 10th Grade" );
number1 = Integer.parseInt ( firstNumber);
number2 = Integer.parseInt ( secondNumber);
number3 = Integer.parseInt ( thirdNumber);
number4 = Integer.parseInt ( fourthNumber);
number5 = Integer.parseInt ( fifthNumber);
number6 = Integer.parseInt ( sixthNumber);
number7 = Integer.parseInt ( seventhNumber);
number8 = Integer.parseInt ( eighthNumber);
number9 = Integer.parseInt ( ninethNumber);
number10 = Integer.parseInt ( tenthNumber);
sum = (number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8 +number9 + number10)/10;
JOptionPane.showMessageDialog (
null, "The Average is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
if (sum < 50){
JOptionPane.showMessageDialog (
null, "Fail", "Results",
JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog (
null, "Pass", "Results",
JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}

Woah there, that's a lot of repetition. You should probably clean this up with loops, like:
double sum = 0; // initialize variable for sum of all the numbers
for (int i = 1; i <= 10; i ++) { // go from 1 to 10
String strNum = JOptionPane.showInputDialog("Enter grade #" + i); // prompt for input
double dNum = Double.parseDouble(strNum); // convert to double
sum += dNum; // add to sum
}
double avg = sum / 10; // now get the average

number1 = Integer.parseInt ( firstNumber); expects to recieve a string that "looks like" an integer, if you give it something that "looks like" anything else you will recieve an error. You should instead use Double.parseDouble(firstNumber);
And yes, you should absolutely use an array for this. The use of arrays allows for a far shorter program;
public class UseArrays {
public static void main(String[] args){
int numberOfEntries=10
double[] numbers =new double[numberOfEntries];
for(int i=0;i< numbers .length;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
numbers[i]=Double.parseDouble(option);
}
double sum=0;
for(int i=0;i< numbers .length;i++){
sum+=numbers[i];
}
double average=sum/10;
System.out.println(average);
}
}
Note also that with the program created in this way it is incredibly easy to change the number of entries, in addition to being much shorter to write. You would not want to type out each entry by hand if you had hundreds, thousands or even millions of entries.
You could make this program even shorter by not storing each double then adding them later (which would also make using the array unnessissary). This program would look like;
public class DontUseArrays {
public static void main(String[] args){
int numberOfEntries=10
double sum=0;
for(int i=0;i< numberOfEntries;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
double number=Double.parseDouble(option);
sum+=number;
}
double average=sum/10;
System.out.println(average);
}
}

Here's a fragment of code that should get you on your way:
public void test() {
double[] numbers = new double[10];
double sum = 0;
for ( int i = 0; i < numbers.length; i++ ) {
String number = JOptionPane.showInputDialog ( "Enter Grade "+(i+1) );
numbers[i] = Double.parseDouble(number);
sum += numbers[i];
}
}

What if you had to calculate 1000 grades? That's why we use arrays.
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail
{
public static void main(String[] args)
{
String[] mumStr = new String[10];
double sum = 0;
for (int i = 0; i < numStr.length; i++) //0 to 10 (10 not included)
{
numStr[i] = JOptionPane.showInputDialog ( "Enter Grade " + (i+1)+ ": " );
sum += Double.parseDouble(numStr[i]);
}
double avg = sum / numStr.length;
JOptionPane.showMessageDialog (null, "The Average is " + avg, "Results", JOptionPane.PLAIN_MESSAGE);
if (avg < 50)
{
JOptionPane.showMessageDialog (null, "Fail", "Results", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog (null, "Pass", "Results", JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}

To parse your Strings to the double type use Double.parseDouble(String s)
You can assign the ints returned from Integer.parseInt(String s) to your double variables, because doubles are higher precision than ints and so type conversion happens automatically without the need for an explicit cast.
However you can not parse any String with a decimal point to an int using Integer.parseInt(String s), by definition.
Additional point - There's no need to declare the String variables, or have a separate variable for each number - it'll be much cleaner to use an array and a loop to input the numbers, and possibly sum the numbers as they come in, something like:
double[] numbers = new double[10];
double sum = 0d;
for(int i = 0; i < numbers.length; i++ ) {
numbers[i] = Double.parseDouble(JOptionPane.showInputDialog ( "Enter 1st Grade" ));
sum += numbers[i];
}
double mean = sum / numbers.length;

Related

How to remove the dot?

I started to study JAVA, So sorry for the question.. I practice the WHILE LOOP, so I have this code:
import java.util.Scanner;
public class Class {
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
double n = 0;
while ( n < 10 )
{
System.out.println( (n+1) + "." + message );
n++;
}
}
}
so, I want to get a result somthing like that: 10. 20. 30. and etc..
but I get: 1.0. , 2.0., 3.0. and etc..
what I should do to remove this dot, between 1 and 0...? thank you very much for your help :).
Use int instead of double for n variable:
int n = 0;
Well, a quick fix to your problem would be first changing the data type to int, so int n = 0; then simply add "0." to your print statement, so it looks like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 0;
while ( n < 10 ) {
System.out.println( (n+1) + "0." + message );
n++;
}
}
}
Or, alternatively, you could do int n = 10 and have your while loop condition aswhile( n < 100 ) then increment n by ten (n+=10;). So now it would look like:
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Type in a message" );
System.out.print( "Message: " );
String message = keyboard.nextLine();
int n = 10;
while ( n < 100 ) {
System.out.println(n + "." + message);
n+=10;
}
}
}
you can increment in 10s by multiplying n by 10, Also you might want to use int type rather than double to remove the decimal point.
int n = 1;
while ( n <= 10 )
{
System.out.println( ( 10 * n) "." + message );
n++;
}
You can try something like this:
int n = 10; // start from 10 and change it from double to int to get rid of decimal point
while ( n <= 100 ){
System.out.println( n + "." + "message");
n+=10; // increment by 10 after every loop
}

I keep on getting an Exception in thread "main" java.lang.NumberFormatException: For input string: "exit"

My code looks like this. It compiles fine and runs fine until I enter "exit" in the JOptionPane window. "exit" is meant for the code to stop and display the average, min, max, and range. When I enter exit it prints
Exception in thread "main" java.lang.NumberFormatException: For input string: "exit"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at Loop2.main(Loop2.java:41)
import javax.swing.JOptionPane;
public class Loop2
{
public static void main(String [] args)
{
float max = 0;//Integer.MIN_VALUE;
float min = 0;//Integer.MAX_VALUE;
float sum = 0;
float num = 0;
int count = 0;
float average = 0;
float range = 0;
String userInput;
userInput = JOptionPane.showInputDialog( "Enter a value. " , null);
num = Float.parseFloat(userInput);
if (!userInput.equals("exit"))
{
num = Float.parseFloat(userInput);
min = num;
max = num;
}//end if
while (!userInput.equals("exit") )
{
sum = sum + num;
count++;
if( num > max )
{
max = num;
}
if( num < min )
{
min = num;
}
userInput = JOptionPane.showInputDialog( "Enter a value. " , null);
num = Float.parseFloat(userInput);
} //end while
average = (sum) / (count);
System.out.println( "Average: " + average );
range = (max) - (min);
System.out.println( "Range: " + range );
System.out.println( "Minimum value: " + min );
System.out.println( "Max value: " + max );
}
}
You're trying to convert "exit" into a float, which isn't possible. You should check for the "exit" string before casting to float
First, you parse float, and then you check if it is "exit", and then parse float again:
userInput = JOptionPane.showInputDialog( "Enter a value. " , null);
num = Float.parseFloat(userInput);
if (!userInput.equals("exit"))
{
num = Float.parseFloat(userInput);
You are trying to parse 'exit' as a number, simply remove the first call to Float.parseFloat, as you are calling this if the user hasn't typed exit anyway.
The problem is that you are trying to parse "exit" to a float before checking for exit.
num = Float.parseFloat(userInput);
if (!userInput.equals("exit"))
{
Try this instead:
if (!userInput.equals("exit")){
num = Float.parseFloat(userInput);
Float.parseFloat(string);
The parseFloat method returns the exception NumberFormatException if the string does not contain a parsable float. Check your string input.

Divide Euro Amount

I have a problem in my code and i can't find the answer for it.
I only can use if and else and can't use other classes for an example Math.
The code save a value and try to divide in euro coins.
If i enter 4,31 the result is 2x2e + 1x20c + 1x1c and this is ok but if i enter the value 1,20 the result is 1e + 1x10c + 1x5c + 2x2c + 1x1c but the right result is 1e + 1x20c.
I had to add 0.001 in the 1cent coin because if i don't i'll not get a print for it. Adding this is wrong too.
If somebody could help me i would be very grateful.
Regards.
Code:
import java.util.Scanner;
public class Coins {
public static void main(String[] args){
Scanner in= new Scanner(System.in);
int e2 = 0, e1 = 0,c50 = 0, c20=0,c10 = 0,c5 = 0,c2 = 0,c1;
double v;
System.out.println("Quantia em euros: ");
v = in.nextDouble();
e2 = (int)v/2;
v=v-e2*2;
e1=(int)v;
v=(v-e1)*100;
c50=(int)v/50;
v=v-c50*50;
c20=(int)v/20;
v=v-c20*20;
c10=(int)v/10;
v=v-c10*10;
c5=(int)v/5;
v=v-c5*5;
c2=(int)v/2;
v=v-c2*2;
c1=(int)(v+0.001);
if(e2!=0)System.out.print(e2+"X2Eur ");
if(e2!=0&&!(e1==0&&c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(e1!=0)System.out.print(e1+"X1Eur ");
if(e1!=0&&!(c50==0&&c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c50!=0)System.out.print(c50+"X50c ");
if(c50!=0&&!(c20==0&&c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c20!=0)System.out.print(c20+"X20c ");
if(c20!=0&&!(c10==0&&c5==0&&c2==0&&c1==0))System.out.print("+ ");
if(c10!=0)System.out.print(c10+"X10c ");
if(c10!=0&&!((c5==0&&c2==0&&c1==0)))System.out.print("+ ");
if(c5!=0)System.out.print(c5+"X5c ");
if(c5!=0&&!(c2==0&&c1==0))System.out.print("+ ");
if(c2!=0)System.out.print(c2+"X2c ");
if(c2!=0&&!(c1==0))System.out.print("+ ");
if(c1!=0)System.out.print(c1+"X1c");
}
}
first of all: if you store a value in a double-variable, always consider that double is a bit imprecise, i'd use cents instead (simply remove the comma and parse to int).
for the implementation itself: optimize the whole thing using arrays.
final int[] coin_values = new int[]{
200 , 100 , 50 , 20 , 10 , 5 , 2 , 1};
final String[] coin_names = new String[]{
"2€" , "1€" , "50ct" , "20ct" , "10ct" , "5ct" , "2ct" , "1ct"};
String input = in.next();
String[] temp = input.split(".");
input = temp[0] + temp[1];
int value = Integer.parseInt(input);
int[] coins = new int[coin_values.length];
for(int i = 0 ; i < coins.length ; i++){
coins[i] = value / coin_values[i];
value %= coin_values[i];
if(coins[i] != 0)
System.out.print(coins[i] + " " + coin_names[i] + " + ");
}
These are rounding errors by Java, they can always occur when using floats. In your case you keep editting the same value so the error gets bigger and bigger.
Use
System.out.println("Quantia em euros: ");
v = 1.20;
int cents = (int)(v*100);
e2 = cents/200;
cents = cents%200;
e1=cents / 100;
cents = cents % 100;
c50=cents/50;
cents = cents%50;
c20=(int)cents/20;
cents = cents %20;
c10=(int)cents/10;
cents = cents%10;
c5=(int)cents/5;
cents = cents % 5;
c2=(int)cents/2;
c1=cents%2;
Because rounding errors don't occur on ints.
In Java always use java.math.BigDecimal for monetary amounts.
You won't get strange rounding behaviour that you can't control.

Average of an array and associate with name

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

Java 2 dimensional arrays and average

Can someone please help me with this homework?
I have tried something but I'm not sure if my solution covers all the tasks.
I have to write a Java program, which initializes a two-dimensional array with the marks from the 5th semester (there are only 5 marks, as you know) of n students (the user should input the number of students).
The program should outputs as a result:
The average grade of all students for 5th semester;
The number of the student with the highest average grade;
The number of the student with the lowest average grade;
The number of students with an average grade greater than the average grade of all students;
The number of students with an average grade less than the average grade of all students;
The program should do data validation as follows: student’s marks should be between 2 and 6, and the number of students should not exceed 30.
and here is my solution so far :
package ocenki;
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + i +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
System.out.println("The average is " + sum/5 + ", the minimum is " + min + " and the maximum is " + max);
}
Please find the solution for your Q-4 AND Q-5
Solution
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
FULL CODE -
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + (i+1) +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
int lessAvg=1,moreAvg=0;
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
System.out.println("The average is " +avg + ", the minimum is " + min + " and the maximum is " + max);
System.out.println("4.The number of students with an average grade greater than the average grade of all students"+moreAvg);
System.out.println("5.The number of students with an average grade less than the average grade of all students"+lessAvg);
}

Categories

Resources