This Java program is for finding the data from a txt file that consists a number of integers. I have figured out the codes for the maximum, average to run the program. For a lot of you it should be simple but I am relatively in-experienced in programming so bear with me.
There are three codes that I am having trouble are as follows.
number of numbers above average
number of prime numbers
finding the total sum
Does anyone know a way to do this?
Thanks. Any advice helps.
Here is the txt file sample of 20 numbers
1
12
34
54
36
76
67
86
45
44
33
22
2
4
7
87
89
99
432
543
List item
package Assignment1;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Define two arrays - local variables
// Declaring 10 integers
int[] myIntArray = new int[20];
// Declaring 10 strings
//File
File f = new File ("inputassignment1.txt");
try {
Scanner sc = new Scanner(f); //Scanner
for (int i=0; i < myIntArray.length; i++) {
myIntArray[i] = sc.nextInt();
}
// Closing the file
sc.close();
} catch (IOException e) {
System.out.println("Unable to create : "+e.getMessage());
}
System.out.println("Highest number: " + maxNum(myIntArray));
System.out.println("Average number: "+aveNum(myIntArray));
// System.out.println(allNum(myIntArray));
// System.out.println(avgPlus(myIntArray));
}// end of main
Let's break your task down:
There are 3 overall tasks:
Count how many numbers are above average
Find the total sum
Find all the prime numbers
Each of these requires you to:
Read in numbers from a text file (into an array probably)
Perform some checks on them (e.g. if isPrime(number) { primes[numPrimes] = number; numPrimes++; })
Count how many there are (numNumbers++, for each number)
Sum them up (totalSum += number, for each number)
For the first one you will need to add another loop after you have the count/sum, the the other two should be doable by modifying the first loop (I have shown an example below).
I think you should be able to google for how to do each of those. Your code above looks like a good starting point.
int numNumbers = 0;
int totalSum = 0;
for (int i=0; i < myIntArray.length; i++) {
myIntArray[i] = sc.nextInt();
numNumbers++;
totalSum += myIntArray[i];
}
Related
I've written some code that has a scanner read from a text file on my computer, but when running the code, the scanner only reads every other number that's in the text file.. any ideas?
Note: For the grades.txt, this is the file
"3 8 1 13 18 15 7 17 1 14"
import java.util.*;
import java.io.*;
public class GradeAverage
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("C:\\Users\\Media - Graphics\\Documents\\SCHOOL\\NCVPS\\GradeAverage\\grades.txt"));
int i = 0;
int sum = 0;
int lineNumber = 0;
int average = 0;
while(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
lineNumber++;
}
System.out.println("The sum of the numbers: "+sum);
System.out.println("The number of scores: "+lineNumber);
average = sum/lineNumber;
System.out.println("The average of the numbers: "+average);
}
}
Here's what it outputs:
3
1
18
7
1
The sum of the numbers: 67
The number of scores: 5
The average of the numbers: 13
Every time you call nextInt() in your loop, you consume one int. So when you do
System.out.println(scanner.nextInt());
sum = sum+scanner.nextInt();
You consume two int(s). You want something like
int t = scanner.nextInt();
System.out.println(t);
sum += t;
Also your average is currently an int (I would expect a float or double).
double average = sum/(double)lineNumber;
Don't forget to remove int average = 0; (or modify this and average accordingly).
(It's my homework task. So I can't make any changes to the task like changing the rules of input.)
I need to calculate
a^m mod n
and print out the result. (I've already figured out how to code the calculation.)
But the question said there'll be multiple lines of input:
IN:
12 5 47
2 4 89
29 5 54
and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)
OUT:
14
16
5
The code I've tried so far:
import java.util.Scanner;
public class mod {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int count = 0;
while (input.hasNextLine()){
count++;
}
int[] array = new int[count];
for (int i = 0; i < count; i ++){
int a = input.nextInt();
int m = input.nextInt();
int n = input.nextInt();
int result = (int)((Math.pow(a, m)) % n);
array[i] = result;
}
for (int x : array){
System.out.println(x);
}
}
}
I tried to count the lines of input and build an array of that size to store the results.
But it seems my code fail to detect the end of input and keep looping.
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
} else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
lines.add(line);
}
}
int count = lines.size();
for (int i = 0; i < count; i++) {
String[] tokens = lines.get(i).split("\\s+");
int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
n = Integer.parseInt(tokens[2]);
int result = (int) ((Math.pow(a, m)) % n);
System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
I tested with your provided input,
12 5 47
2 4 89
29 5 54
(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5
This is the code I have and i'm confused about how to set it up. I'm fairly new to coding so any input would help. When I execute the code I get 10 random numbers which is what I want but the max always comes out to be 10.
import java.util.*;
import java.util.Scanner;
public class Question2Chapter4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int max = 0;
int counter;
Random num = new Random();
System.out.println("Random numbers are:");
for (counter = 1; counter <= 10; counter++) {
System.out.println(num.nextInt(100));
if (max < counter) {
max = counter;
}
}
System.out.println("Largest number is " + max);
in.close();
}
}
Here is an example of one of the outputs:
Random numbers are:
73
66
64
89
57
75
60
47
74
29
Largest number is 10
You are not storing the random value in your max variable. Instead you are storing the counter variable which maximum value will be 10(as defined in your loop). So replace your loop code to this:
int number = num.nextInt(100); // store your random number
System.out.println(number);
if (max < number) {
max = number;
}
If you want the minimum value add another variable and another if statement:
int min = 100; // before the loop
...
if (min > number) { // inside the loop and after the random number is generated
min = number;
}
First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:
Program asks user how many grades there are.
Program asks user for each grade (for loop needed and should sum grades within loop).
Take sum of all grades, compute average and store in a float variable grade.
Print grade value to console and append a number to a string such as "Grade Average is: " + grade
Example should read as:
Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5
My code so far (not much here):
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}
Edit:
// This program computes the letter grades for number of grades given by user
import java.util.*;
public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;
System.out.println("The average of the grades is: " + sum/count);
}
}
This is what I have now, however a test displays incorrect results (example):
Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0
Each grade needs to be entered on separate lines so the averaging is skewed as a result.
import java.util.Scanner;
public static void main(String[] args) {
int count = 0;
float sum = 0;
float grade = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of grades: ");
count = scan.nextInt();
for (int i = 0; i < count; i++) {
System.out.print("Enter grade no " + (i + 1) + " : ");
grade = scan.nextFloat();
sum += grade;
}
System.out.println("Sum = " + sum);
System.out.println("Average = " + sum / (float) count);
}
Break the big task into smaller tasks , like #user2864740 said , write the algorithm (not code) on a paper then start translating that to code
u reached the part where u created a scanner to read input , now read the input and ....figure out the rest .
To learn how to read user input read this.
To learn how to make an integer out of Strings ur scanning read this
the rest is basic math really , read your textbook , and good luck ;)
edit : at least come out with some algorithm then maybe we'll help with the code
I won't solve the homework for you, I will help you however:
How to use a for loop:
for (int i = #startValue#; #booleanCondition#; #runTheFollowingCodeAtEachIteration#)
{
//code
}
ex:
for(int i = 0; i<10; i++)
{
System.out.println(i);
}
will display:
0
1
2
3
4
5
6
7
8
9
Your homework:
Program asks how many grades there are:
Scan a value called NumberOfGrades (called count in your code) inputted by the user.
Program asks user for each grade + sums the grades:
Use a for loop, with a starting value of i, and a upper limit of NumberOfGrades. Scan each grade and add it to a value called GradeSum, which initially should be 0 before entering the for loop.
Print value to console... :
Divide GradeSum by NumberofGrades, and display it how you would like it to be displayed.
Tips:
-Use System.out.print("\nEnter grade: "); in your for loop before each scan.
To avoid directly answering your homework question (which both won't help you get it and is probably not allowed), let's start with "what is a for loop?"
A for loop is a fancy loop that does the following things for you:
Initializes one (or more) variables to initial values the first time the loop statement is executed
Each iteration, checks a boolean condition to determine if it should loop again. If the expression evaluates to true, iterate again. Otherwise, break the loop and continue with the code following the loop.
A statement that is run each time the loop finishes iterating.
For example, the following loop would print the numbers 1 .. 10.
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
The first part of the loop statement int i = 1 is the initialization block. i is initialized to an int with value 1 when the for loop is executed for the first time.
The second part of the loop statement i <= 10 is the boolean condition to check to determine if another iteration is required. In this case, i <= 10 evaluates to true if i is less than or equal to 10, and false once i hits 11 (or any larger number).
Finally, the third part i++ is the statement run when the for loop finishes an iteration. i++ adds 1 to the current value of i, thus i will increase in value by 1 each iteration.
I'm writing this program with numbers, but I am stuck and need some help.
Code so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Oppgi øvre grense: ");
int Number = in.nextInt();
int tall = 1;
for(int t = 0; tall <=45; tall++){
System.out.println(" " + tall);
}
}
The objective: to get the first line to contain one number, the second to contain two numbers, third line contain three numbers, etc.
The output should look like a pyramid, with different spacing between the numbers on each line.
If anybody can help me with the solution code. Thank you.
Oppgi øvre grense: 45
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
outer loop{
decides number of numbers in one line
inner loop{
prints actual numbers.
Please keep track of the numbers you have printed so far
Inner loop starts at numbers printed so far
It will have passes = number of numbers to print
}
}
You have two distinct tasks here:
1. Decide how many numbers to print in one line
2. Actually print the numbers
Since that is the case, one loop decides how many numbers to print: the outer loop. The Reason it is outer loop is because you need to have a clear picture of how many numbers you need to print before you actually print.
The other loop: inner loop does the actual printing.
So, once you start with the outer loop, your inner loop will begin printing.
It will then see if it has printed the maximum number of numbers for that pass.
If yes, stop. Then, you increment the outer loop. Come back in, print, check and then do the same.
Easy enough ?
public class RareMile {
public static void main (String[] args){
printNum(5);
}
public static void printNum (int n){
int k=1, sum=0;
for (int i=1; i<=n; i++){
sum=0;
for(int j=1; j<=i; j++){
System.out.print(k);
sum = sum+k;
k++;
}
System.out.print(" =" + sum);
System.out.println();
}
}
}
The real question is that how to do it with only one for loop?
Keep track of the line number
e.g.
int line = 1; // line number
int count = 0; // number of numbers on the line
for(int x = 0; x <= 45; x++){
if (count == line){
System.out.println(""); // move to a new line
count = 0; // set count back to 0
line++; // increment the line number by 1
}
System.out.print(x); // keep on printing on the same line
System.out.print(" "); // add a space after you printed your number
count++;
}