I've been spinning my wheels on a homework assignment for the last 3 hours and am not making very much progress. I was wondering if someone could help nudge me in the right direction.
The assignment is to read data from a file and convert it to something that is more reader friendly. The data file looks something like this:
0.30 0.30 0.40
161
3333 70 60 50
4444 50 50 50
5555 80 90 80
0
162
1212 90 85 92
6666 60 80 90
7777 90 90 90
8888 95 87 93
9999 75 77 73
0
263
2222 90 65 75
8989 60 40 60
9090 70 80 30
0
The file contains 5 different types of numbers.
1. The three digit numbers are course numbers.
2. The four digit numbers are student numbers.
The two digit numbers are scores for assignments, mid terms, and finals for each student.
The decimals across the top are used to find the weighted average for the scores.
zeros are a break between courses.
I am supposed to read all of the data in the file and then format and output it so it's easy to read:
Grade Data For Class 161
ID Programs Midterm Final Weighted Average Programs grade
-- -------- ------- ----- ---------------- --------------
3333 70 60 50 59.00 Pass
4444 50 50 50 50.00 Fail
5555 80 90 80 83.00 Pass
Class Average: 64.00
I have the scanner setup and am able to parse out the numbers from the text, my problem is that they are all saved as Strings so I can't do any mathematical checks on them. I'm starting to wonder if this is even the best way to go about this.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classID;
System.out.println("ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println("-- -------- ------- ----- ---------------- --------------");
while(in.hasNextLine()) //While file has new lines
{
//line equals each line of text
String line = in.nextLine();
Scanner lineParser = new Scanner(line);
System.out.println(line);
for(; lineParser.hasNext();)
{
//number = each number
String number = lineParser.next();
System.out.println(number);
if(number < 1 && number > 0)
{
double programsAverage = number.nextDouble();
double midtermAverage = number.nextDouble();
double finalAverage = number.nextDouble();
System.out.println(programsAverage);
System.out.println(midtermAverage);
System.out.println(finalAverage);
}
}
}
}
}
Update I've included my updated code. My problem now is my conditions in my for statements. These should be checking the values of the incoming Scanner data to see if the data is:
a weight calculator(0,1)
a score(1,100),
a classNumber (100,400),
a studentNumber(1000,9999),
a class separator (0).
I am thinking something like:
for(in.next(); in < 100 && in > 1; next());
This isn't quite doing it though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
/**
* Write a description of class classAverage here.
*
* #author
* #version
*/
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classNumber;
int studentNumber;
int programs;
int midterm;
int finals;
double programWeight = in.nextDouble();
double midtermWeight = in.nextDouble();
double finalWeight = in.nextDouble();
//System.out.println(programWeight + " " + midtermWeight + " " + finalWeight);
for(int k = 0; k < 3; k++)
{
for(int i = 0; i <= 0; i++)
{
classNumber = in.nextInt();
System.out.println("Grades for class: " + classNumber);
System.out.println(" ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println(" -- -------- ------- ----- ---------------- --------------");
}
int studentCount = 0;
double sumAverage = 0.0;
for(int j = 0; j <= 2; j++)
{
studentNumber = in.nextInt();
programs = in.nextInt();
midterm = in.nextInt();
finals = in.nextInt();
studentCount++;
double weightedAverage = (programWeight * programs) + (midtermWeight * midterm) + (finalWeight * finals);
sumAverage += weightedAverage;
System.out.printf("%d %d %d %d %.2f ", studentNumber,programs,midterm,finals,weightedAverage);
if(programs >= 70)
{
System.out.print("PASS");
} else {
System.out.print("FAIL");
}
System.out.println();
}
double classAverage = sumAverage / studentCount;
System.out.printf("Class average is: %.2f", classAverage);
System.out.println("\n\n");
}
}
}
You have 2 options here :
Use Scanner#hasNextInt() and nextInt() instead of nextLine() to read Integers directly instead of numbers in String format.
Keep your reading / scanning code intact. Use Integer.parseInt() to convert String to Integers. --> Preferred solution. As it is more efficient.
Related
I was just practicing java programming by myself using random and averaging numbers but I was having a difficult time to do it. The program will ask "Enter # to be rolled between 0 to 100". Then I enter '3' then the output will be random 3 numbers.
My question is after 3 numbers come out, I want to find the average of those numbers. For example, I want my output to be
Your # is 89
Your # is 50
Your # is 12
Your avg is ##(//whatever the avg of numbers)
My output is like
Enter # to be rolled between 0 to 100
3
Your # is 89
your avg is 29
Your # is 39
your avg is 13
Your # is 76
your avg is 25
Can you guys help me to solve this problem? I know my codes are mess.
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran;
System.out.println("Enter # to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}
You need to define avg outside of the loop and then add all your numbers to it. It's also better to call it sum and define it as double to prevent rounding, this way you can divide it by number after the loop and get the average.
double sum = 0;
for(int i=0; i<number; i++) {
// ...
sum += ran;
}
System.out.println("your avg is " + sum/number);
int sum=0;
for(int i=0; i<number; i++) {
ran=ranNumber.nextInt(100);
System.out.println("Your # is " + ran);
sum = sum+ran;
}
System.out.println("your avg is " + sum/number);
it's tested :
user must enter a number integer :
import java.util.Random;
import java.util.Scanner;
public class ranEx {
public static void main(String[] args) {
Random ranNumber = new Random();
Scanner input = new Scanner(System.in);
int number;
int ran = 0;
System.out.println("Enter A NUMBER to be rolled "
+ "between 0 to 100");
number = input.nextInt();
for(int i=0; i<number; i++) {
ran=ran+(ranNumber.nextInt(100));
System.out.println("Your # is " + ran);
int avg=ran/number;
System.out.println("your avg is " + avg);
}
}
}
output :
run:
Enter A NUMBER to be rolled between 0 to 100
5
Your # is 95
your avg is 19
Your # is 107
your avg is 21
Your # is 178
your avg is 35
Your # is 274
your avg is 54
Your # is 338
your avg is 67
BUILD SUCCESSFUL (total time: 2 seconds)
You want the compute the average only once, outside the loop, after the loop generates the values. You could accomplish your goal as follows:
Intialize an accumulator variable to zero before the loop
Inside the loop, add each generated value to the accumulator
After the loop, divide the accumulator value by the number of values
If you just want the average, define a variable that keeps the accumulate total, and then divide by the number of rolls.
// double for large values and decimal division later on
double total= 0;
int rolls = 4;
for ( int x = 0 ; x < rolls; x++ ) {
total += x;
}
// calculate average
double average = total / rolls;
// validate that it works, ( ( 0 + 1 + 2 + 3 ) / 4 ) == 1.5
Assert.assertEquals( 1.5d, average );
I have a Printf formating question. I am to print only 10 numbers, before going to the next line and printing 10 more numbers and so on. with the end goal being like a table, with all the columns lining up and being aligned to the right. I am using a while statement as well. I have tried a few different things that I have found in my research, with no success. Would I use a different print statement for it other than Printf? Such as Print, or PrintLn? Also thought about using an If statement as well. Any help would be greatly appreciated! Thank you.
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
}
Using a MOD condition, You can ensure 10 output per line.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
System.out.printf("Please enter a maximun integer value: ");
Scanner scan = new Scanner(System.in);
double n = scan.nextDouble();
System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct
double startNum = 0;
double sqrt = startNum;
System.out.printf("Squares less than %.0f are: ", n);
while (sqrt < n) {
sqrt = Math.pow(startNum, 2);
if(startNum != 0 && startNum % 10 == 0) {
System.out.println();
}
System.out.printf("%6.0f", sqrt);
startNum++;
}
}
}
Output -
Please enter a maximun integer value: 150
The number you entered was: 150
Squares less than 150 are: 0 1 4 9 16 25 36 49 64 81
121 144 169
while ( sqrt < n) {
sqrt = Math.pow(startNum, 2);
System.out.printf("%6.0f", sqrt);
startNum ++;
if(startNum%10==0){
System.out.printf("/n");
}
}
Here is a quick look at the program that I made to give a better example of my question.
Loop code
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
This is what my program outputs
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44
This work can be up to 4 days late before failing.
This is what the output is supposed to be
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24
This work can be up to 4 days late before failing.
I have to display how many days late the assignment is and calculate the late penaltie (mark -5) I also have to display the number of days needed needed to fail the assigment ( number of days until failure might be larger than the number (d) of days that the user input ) . the failing mark is less than 40.
2nd example (output)
Please input mark: 64
Please input number of days to display: 2
Scheme 1
(0) 64 (1) 59 (2) 54
This work can be up to 4 days late before failing.
I have almost complete my code but this problem is slowing me down.
P.S. I am new at java
here is my full program
LatePenalties calss
public class LatePenalties {
// attributes
private int mark;
private static final int constantDiffSch1 = -5;
private static final double constantDiffSch2 = 0.9;
private static final int START_CONDITION = 0;
// constructors
public LatePenalties(int m) {
mark = m;
}
// methods
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
public void scheme2(int d) {
double total = mark;
System.out.print("\n\nScheme 2"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print( "(" + loopParameter + ") " );
System.out.printf("%.02f",total);
System.out.print(" ");
total = total * constantDiffSch2;
} // End
System.out.print("\n");
}
}
Main class
import java.util.Scanner;
public class LatePenaltiesUser {
public static void main(String [] args) {
// local variables
Scanner input = new Scanner(System.in);
LatePenalties latePen;
int mark;
int days;
// input
do{
System.out.print("Please input mark (between 0 and 100) --> ");
mark = input.nextInt();
if (( mark < 0 ) | (mark > 100 )){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while(( mark < 0 ) | (mark > 100 ));
do{
System.out.print("Please input number of days to display (between 0 and 20) --> ");
days = input.nextInt();
System.out.print("\n");
if (( days < 0 ) | (days > 20 )){System.out.print("Input value outside the range!!!"+ "\n");}
}while(( days < 0 ) | (days > 20 ));
// computation
latePen = new LatePenalties(mark);
latePen.scheme1(days);
latePen.scheme2(days);
}
}
I have to show when the faling mark occurs(at less than 40), but I have to stop the loop at 20 or when the number of days is reached, as I show in the example on what it is expected.
You can use break to come out of the loop as soon as total is less than 40. You can update your scheme1 method as below
public void scheme1(int d) {
int total = mark;
System.out.print("Scheme 1" + "\n");
int days = 0;
// Loop
for (int loopParameter = START_CONDITION; loopParameter <= d; loopParameter++) {
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
if(total < 40)
break;
days++;
} // End
if (total <= 40) {
System.out.print("\nThis work can be up to " + days +" days late before failing.");
}
System.out.print("\n\n");
}
Please input mark (between 0 and 100) --> 82
Please input number of days to display (between 0 and 20) --> 10
Scheme 1 (0) 82 (1) 77 (2) 72 (3) 67 (4) 62 (5) 57 (6) 52
(7) 47 (8) 42
This work can be up to 8 days late before failing.
You don't need to know your loopParameter to calculate the number of days. You can calculate it like so:
int days = (d - 40) / -constantDiffSch1;
You can use break when you want to quit loop. So:
if (total < 20) break;
And off topic. Don't call loopParameter like that. It is good practice to call it in one symbol (or short word) like i or day. It makes code easier to read and understand.
So, I am done with first part and most of 2nd one but can not figure out how to do Palindromic primes, so please help. The code i am attaching is p1b and I have no idea what to do in p1c so please help.
I. Introduction:
The purpose of this project is to help you learn the basic JAVA programming language
elements based upon your C/C++ background that you gained from CSC114.
II. Assignment: Develop a JAVA program according to the following steps:
Part A: Name this step p1a.java and you don’t need to write a method other than main
for this.
1) The user is asked to enter an integer and your program is to produce the reverse
of that number.
Example follows:
Please enter an integer number: 2341
The reverse of 2341 is 1432
Part B: Name this step p1b.java.
1) Modify the last step using a method called reverse that returns the reverse value of
a given integer. Then, modify the program so that it will runs as the following:
2) The user is asked to enter two integers, say x and y;
3) So long as x is less than y, your program will do the following:
a) Find and print all prime numbers between x and y. (Need a method called
isPrime that checks whether a given number is a prime or not.)
b) Find and print all prime numbers that are also palindromes;
c) Ask for another pair of x and y.
Example follows:
Please enter two integer numbers: 5 400
Prime:
5 7 11 13 17 19 23 29 31 37
41 43 47 53 59 61 67 71 73 79
83 89 97 101 103 107 109 113 127 131
137 139 149 151 157 163 167 173 179 181
191 193 197 199 211 223 227 229 233 239
241 251 257 263 269 271 277 281 283 293
307 311 313 317 331 337 347 349 353 359
367 373 379 383 389 397
Palindromic Prime:
5 7 11 101 131 151 181 191 313 353
373 383
Please enter two integer numbers: 9 1
Done
Part C: Name this step p1c.java.
1) Traditionally, in order to produce the above output, the approach that one normally
has is to go through the numbers twice: the first time is to find and print all prime
numbers and then go through the numbers again to find and print all palindromic
primes. However, if we are able to keep the result and then print it when the
process is completed, then it will only need 1 pass.
2) Additionally, please display your output in a formatted way (such as aligned output
in the previous page).
3) Modify p1b.java so that it will only go through one pass to produce the same result
as produced in part B.
import java.util.Scanner;
public class p1b {
public static void main(String[] args) {
System.out.println("Program for Finding Primem Numbers: ");
System.out.println("==================================");
Scanner input = new Scanner(System.in);
int num1, num2, i;
int choice;
System.out.print("Please enter the first number: ");
num1 = input.nextInt();
System.out.print("Please enter the Second number: ");
num2 = input.nextInt();
if (num1 > num2) {
System.out.println(" Thank you.");
System.exit(1);
}
System.out.println( isPrime(num1, num2));
System.out.println( reverse(num1));
System.out.print("\nWould you like to enter two more numbers, "
+ "Enter 1 for Yes or 0 for No: ");
choice = input.nextInt();
if(choice == 1) {
System.out.print("Please enter the first number: ");
num1 = input.nextInt();
System.out.print("Please enter the Second number: ");
num2 = input.nextInt();
System.out.println( isPrime(num1, num2));
}
if(choice == 0) {
System.out.println("Bye!!");
System.exit(0);
}
}
public static int isPrime(int num1, int num2) {
final int displayPerLine = 50;
System.out.print("Prime: ");
for ( int i = num1; i <= num2; i++ ) {
int j;
for ( j = 2; j < i; j++) {
int number = i % j;
if (number == 0) {
break;
//return n;
}
}
if(i == j) {
System.out.printf("%-5d " + i);
}
if (i % displayPerLine == 0) {
System.out.println();
}
}
System.out.println();
return num1;
}
//public static int reverse(int num1, int num2) {
public static int reverse(int num1, int num2) {
System.out.print("Palindrome: ");
int palindrome = num1; // copied number into variable
int reverse = palindrome;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (num1 == reverse) {
return reverse;
}
return palindrome;
}
public static int reverse(int num) {
int test = 0;
while (num != 0) {
int lastdigit = num % 10;
test = test * 10 + lastdigit;
num = num / 10;
}
return test;
}
public static boolean isPalindrome(int num) {
return num == reverse(num);
}
}
Let's start by fixing isPrime, first test if the number is even; if so, it isn't prime. Next, test odd numbers from 3 to the square root of the number. If none of those are factors, then the number is prime. Something like,
public static boolean isPrime(int i) {
if (i % 2 == 0) {
return false;
}
double sqrt = Math.sqrt(i);
for (int t = 3; t <= sqrt; t += 2) {
if (i % t == 0) {
return false;
}
}
return true;
}
Then we can implement isPalindrome with a StringBuilder like
public static boolean isPalindrome(int i) {
String str = String.valueOf(i);
return new StringBuilder(str).reverse().toString().equals(str);
}
Finally, we can prompt for input in an infinite (here a while) loop and use an inner for loop for printing primes that are also palindromes. And, you can use Math.max and Math.min for getting the max and min respectively. Like,
public static void main(String[] args) {
System.out.println("\t\tProgram for Finding Prime Numbers: ");
System.out.println("\t\t===================================");
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please enter the first number: ");
int num1 = input.nextInt();
System.out.print("Please enter the second number: ");
int num2 = input.nextInt();
int lo = Math.min(num1, num2);
int hi = Math.max(num1, num2);
for (int i = lo; i <= hi; i++) {
if (isPalindrome(i) && isPrime(i)) {
System.out.println(i);
}
}
System.out.print("Would you like to enter two more numbers, "
+ "Enter 1 for Yes or 0 for No: ");
int choice = input.nextInt();
if (choice == 0) {
break;
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have written code that printed out integers from a .dat file and moved them into a regular array and printed out the average and standard deviation. Now I want to switch from a regular array to an ArrayList. I have written the code below but doesn't seem run correctly.
.dat file includes these numbers: "51 52 55 57 58 61 62 63 66 66 66 70 72 73 74 75 75 77 77 78 79 81 82 84 86 87 88 91 94 97"
Thanks for the help!
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
for (int count = 0; count < element.size(); count++)
{
while (scanner.hasNext())
{
element.add(scanner.nextInt());
number = element.get(count);
for (int item : element){
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
sum += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt((sum / (30-1)));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
}
UPDATE***
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
int newnumber = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
while (scanner.hasNextInt())
{
element.add(scanner.nextInt());
}
for (int item : element){
sum += item;
System.out.println(item);
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
newnumber += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt(newnumber / (element.size()));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
----jGRASP exec: java gradeSorter
51
52
55
57
58
61
62
63
66
66
66
70
72
73
74
75
75
77
77
78
79
81
82
84
86
87
88
91
94
97
The average of these grades is : 73.233
The standard deviation of these grades is: 12.288
----jGRASP: operation complete.
First Issue:
Your for loop doesn't even run once, since element.size() is 0 initially, so the condition of loop will be false at the first iteration only:
for (int count = 0; count < element.size(); count++)
Just remove this loop. You don't need it. An ArrayList can grow dynamically. You don't need to bother about it's size.
Second Issue:
The for loop inside your while loop is doing the danger. It will accumulate the sum of all element, after adding each element. So, your sum won't be the sum of all elements of the list. It would be sum of the elements, added many times. You should move the inner for loop outside the while:
Third Issue:
You are using scanner.hasNext() and reading an int using scanner.nextInt(). You should only test for the element type, that you are reading. Use scanner.hasNextInt() to test for any available integer to read.
Well, there might be some more. But you should first solve these issues, and run the code to see what all parts did you got right.
In all, that part of your code should be modified to:
ArrayList<Integer> element = new ArrayList<Integer>();
// Remove the for loop from here
while (scanner.hasNextInt()) { // Use scanner.hasNextInt()
element.add(scanner.nextInt());
}
for (int item : element) { // Moved this for loop outside the while loop
sum += item;
}
System.out.println(sum);
Remove your for loop and things should run just fine. Just have this:
public static void main(String[] args) throws IOException {
{
....
....
while (scanner.hasNext())
{
number = scanner.nextInt();
element.add(number);
for (int item : element)
{
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
....
....
....
Also details of error you got would be useful.