stop the user from entering an input after the 10th input - java

I'm very new to java and I'm wondering on how to stop the user from entering an input after the 10th. (inputs are separated by space)
sample output would be:
Please type 10 temperatures in Celsius: 30 12 20.5 ..
Temperatures in Celsius: 30.0 12.0 20.5 …
Temperatures in Fahrenheit: 86.0 53.6 68.9 …
Here's my code:
import java.util.Scanner;
public class array {
public static void main(String args[]) {
double [] a = new double [10];
Scanner sc=new Scanner(System.in);
System.out.print("Please type 10 temperatures in Celsius: ");
for(int j=0; j<10; j++)
a[j] = sc.nextDouble();
System.out.print("Temperatures in Celsius: ");
for (int i=0;i<a.length;i++)
System.out.print(a[i] + " ");
System.out.print("\nTemperatures in Fahrenheit: ");
for (int i = 0; i < a.length; i++)
a[i] = a[i]*1.8+32;
for (int i = 0; i < a.length; i++) {
System.out.printf("%.1f ", a[i]);
}
}
}

This is not possible, because input is provided from a terminal/shell, and this terminal usually reads input linewise. You have to do much more low level coding to handle scenarios like these.
Just output an error if the users enters more than 10 values and let him enter them again.

Daniel is correct, with your current setup its not quite possible. You could do it, if you're ok with the console looking a bit different. This requires more 'Enter' presses, and moves each temp to its own line.
Enter 10 temps:
Enter 1: [user input here]
Enter 2: [user input here]
etc etc
System.out.println("Enter 10 temps");
for(int i = 1; i <= 10; i++){
System.out.print("Enter " + i + ":");
a[i-1] = scanner.nextDouble();
}

And you can do some thing like this evry time put a number fo 10 times for each will print temperture in Celsius and in Fahrenheit
public static void main(String args[]) {
int counter = 0;
double[] a = new double[10];
Scanner sc = new Scanner(System.in);
System.out.print("Please type temperatures in Celsius: ");
while(counter < 10){
a[counter] = sc.nextDouble();
System.out.println("Temperatures in Celsius: " + a[counter]);
double tF = a[counter]*1.8 + 32;
System.out.println("Temperatures in Fahrenheit: " + tF);
counter++;
}
}

Related

Needs to identify if input is greater than 90 and print those values and identify if the input is less than 60 and print those values

The program needs to ask the user how many courses it took which is the number of elements in the array. Then it needs to identify which grades are below 65 and print those and then identify which grades are above 90 and print those. Right now, the output just prints 0,1,2,3,4,5 after asking the user for how many courses they took and their grade in each of the course.
import java.util.Scanner;
import java.util.ArrayList;
public class StudentApplication {
public static void main(String[] args) {
Scanner Number = new Scanner(System.in);
System.out.print("How many courses did you take during the school year: ");
int x= Number.nextInt();
int grades[] = new int[x];
for (int courses =1; courses<=x; courses++) {
System.out.print("Enter your grade for that course: ");
Number.nextInt();
int y = Number.nextInt();
}
for (int counter = 0; counter < grades.length; counter++) {
if (counter < 65) {
System.out.print(counter);
}
if (counter >90) {
System.out.print("\n"+counter);
}
}
}
}
Is this what u want?
Scanner sc = new Scanner(System.in);
System.out.print("How many courses did you take during the school year? : ");
int takeCoursesNum = sc.nextInt();
int grades[] = new int[takeCoursesNum]; // array number start "0" ~ ex) { [0], [1], [2] }
for (int i = 0; i < takeCoursesNum; i++) {
System.out.print("Enter your grade for that course : ");
int grade = sc.nextInt();
grades[i] = grade;
}
for (int i = 0; i < takeCoursesNum; i++) {
if (grades[i] < 65) {
System.out.println("below 65 : " + i);// System.out.println : auto change line. no need \n.
}
if (grades[i] > 90) {
System.out.println("above 90 : " + i);
}
}
I hope it is. Happy Codinging :)

Calculate Average in arrays

I want to calculate the average numbers using arrays. I want the program asks for the amount of grades and after I want to put the grade numbers.
After I want to get the average output in a double.
This is my code so far:
public class Average {
public static void main(String[] args)
{
//int n = MyConsole.readInt("Enter number of grades: " );
int a = MyConsole.readInt("Enter grade 1: " );
int b = MyConsole.readInt("Enter grade 2: " );
int c = MyConsole.readInt("Enter grade 3: " );
int[] numbers = new int[]{a,b,c};
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
Don't know what your class MyConsole is doing, but I guess is a Scanner:
Your code improved will be something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of grades: " );
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter grade "+ (i + 1) + ": ");
int a = sc.nextInt();
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
}
OUTPUT (2 grades):
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 5
Average value of array elements is : 3.0
OUTPUT (5 grades):
Enter number of grades: 5
Enter grade 1: 10
Enter grade 2: 20
Enter grade 3: 30
Enter grade 4: 10
Enter grade 5: 50
Average value of array elements is : 24.0
NOTE
double average = sum / n;
performs an int division, so you won't have any decimal places! I would propose a fast cast:
double average = sum / (double) n;
With new output:
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 4
Average value of array elements is : 2.5
GUESS using your own class:
public static void main(String[] args) {
int sum = 0;
int n = MyConsole.readInt("Enter number of grades: " );
for (int i = 0; i < n; i++) {
int a = MyConsole.readInt("Enter grade "+ (i + 1) + ": ");
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
thank you !
Sorry for the poor explanation.
This is my first question
this it the code after edit:
import java.util.Scanner;
public class Average {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of grades: ");
int n = sc.nextInt();
int sum = 0;
int[] numbers = new int[n];
for(int i=0; i < numbers.length ; i++)
{
System.out.println("Enter grade " + (i + 1) + " :");
int a = sc.nextInt();
sum = sum + a;
}
double average = sum / (double) n;
System.out.println("Average value of array elements is : " + average);
sc.close();
}
}
Program to Calculate Average Using Arrays:
public class Inter1 { //name of the class
public static void main(String[] args) {//main method
int number[]={40,56,23,56,87,23,78}; //declaring the int array
int sum=0;
for (int s:number){ //for each
sum +=s;
}
int ave=sum/number.length; //to get the average
System.out.println("the average is "+ave); //out put
}
}
package inter1;
import static java.time.Clock.system;
import java.util.Scanner;
public class Inter1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int total=0;
System.out.println("Enter how many number that do u wanna enter ?? ");
int num= in.nextInt();
int numbers[]=new int[num];
for (int i=0;i<numbers.length;i++){
System.out.println(i+1+":"+"enter the your numbers ? ");
numbers[i]=in.nextInt();
}
for (int i=0;i<numbers.length;i++){
total+=numbers[i];
}
int average =total/numbers.length;
System.out.println("the average is "+average);
}
}
public class Inter1 { //name of the class
public static void main(String[] args) { //main method
System.out.println("==============================");
int num[]={34,56,78,78,34,2,33,99,100,56}; //int array
int total=0;
for (int i=0;i<num.length;i++){ //for loop
total+=num[i];
}
int avrage1=total/num.length; //output
System.out.println("The average is "+avrage1);
}
}

Reading ragged file into a 2d array - print - and find average of columns

I am having trouble reading the entire file and placing it into the array. It keeps leaving out the last 2 numbers in my txt file. What am I doing wrong in my createArr() method that is causing this.
Also, my method avgTimeTemp() is not producing any output other than the first line. I included my text file contents below and output.
Text File Contents
98 95 95 102
99 96
99.5 97
100 97.5 97.5
101 98.5 98 101 100 102.5
99.5
99.5 95 96.5 102 97.5
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Temperature2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//create scanner and read file
File input = new File("lab2input2.txt");
Scanner klg = new Scanner(input);
//Variable declarations
double [][] arr = new double [7][];
System.out.println("Hello! Thank you for saving lives! ");
System.out.println(" ");
System.out.println("Please fill in the data for your patient:");
System.out.println("Patient Name:");
System.out.println("Date(Reporting week): ");
System.out.println(" ");
System.out.println("This Weeks temperature data is incomplete and fragmented... but thats ok! We still have your averages: ");
System.out.println("Your Patients Weekly Temperature Record for Time Classes T1 - T6 are as follows:");
System.out.println(" NOTE: Week starts MONDAY(Day1) and ends SUNDAY(Day7)");
System.out.println(" ");
//Method Calls
createArr(klg, arr);
printArr(arr);
avgDailyTemp(arr);
avgTimeTemp(arr);
klg.close();
} //End of Try
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
} //End of Main
public static void createArr(Scanner klg, double [][] arr) {
int i, j;
for(i = 0; i < arr.length; i++) {
if(arr.length != 7 && arr != null){
System.out.print("There is not data for 7 days in the file you inputed. Please check file contents.");
}
arr[i] = new double[i]; //I Feel I have a problem in this line
for(j = 0; j< arr[i].length; j++) {
arr[i][j] = klg.nextDouble();
}
}
}
//Print array (TESTING PURPOSES)
public static void printArr(double [][] arr) {
System.out.println("The file contains the following input values: ");
for (int i = 0; i< arr.length; i++){
for(int j = 0; j < arr[i].length; j++) {
System.out.println(arr[i][j] + " ");
}
}
}
//The average temperature of a patient each day from Monday to Sunday
public static void avgDailyTemp(double [][] arr) {
double sum, avg;
System.out.println("Average temperature each day this week: ");
for(int i = 0; i < arr.length; i++) {
sum = 0;
for(int j = 0; j<arr[i].length; j++){
sum = sum + arr[i][j];
}
avg = sum/6;
System.out.println("Day " + (i+1) + " " + avg);
}
System.out.println(" ");
}
//NOT WORKING - The average temperature of patient at Time Classes T1-T6
public static void avgTimeTemp(double [][] arr) {
double sum;
System.out.println("Average temperature for each Time Class: ");
for (int j = 0; j < arr[j].length; j++){
double [] avgArr = new double [j];
sum = 0;
for (int i = 0; i < arr.length; i++){
sum = sum + arr[i][j];
}
avgArr[j] =sum/7;
System.out.println("Time Class T" + (j+1) + ": " + avgArr[j]);
}
System.out.println(" ");
}
} //End of Class
OUTPUT:
Hello! Thank you for saving lives!
Please fill in the data for your patient:
Patient Name:
Date(Reporting week):
This Weeks temperature data is incomplete and fragmented... but thats ok! We still have your averages:
Your Patients Weekly Temperature Record for Time Classes T1 - T6 are as follows:
NOTE: Week starts MONDAY(Day1) and ends SUNDAY(Day7)
The file contains the following input values:
98.0
95.0
95.0
102.0
99.0
96.0
99.5
97.0
100.0
97.5
97.5
101.0
98.5
98.0
101.0
100.0
102.5
99.5
99.5
95.0
96.5
Average temperature each day this week:
Day 1 0.0
Day 2 16.333333333333332
Day 3 31.666666666666668
Day 4 49.5
Day 5 65.66666666666667
Day 6 82.66666666666667
Day 7 98.83333333333333
Average temperature for each Time Class:
try
public static void createArr(Scanner klg, double [][] arr) {
int i = 0;
while (klg.hasNextLine()) {
String line = klg.nextLine();
String [] vals = line.split(" ");
arr[i] = new double [vals.length];
int j = 0;
for (String val : vals) {
arr[i][j++] = Double.parseDouble(val);
}
i++;
}
}

Getting highest grade and printing it out using arrays

I want to write a program that can read scores, get the best scores, and assign grades based on that. I have the general idea so far, my problem is figuring out how to incorporate the necessary for-loops. Another problem I have is figuring out how to change line
----(String s1=input.next();) and have the final answer print out the number of entries entered.
I must also use the equation
Grade is A if best score if >= best-10
Grade is B if best score if >= best-20
Grade is C if best score if >= best-30
Grade is D if best score if >= best-40
Ex solution:
Enter number of Students: 4
Enter 4 scores: 40 55 70 58
Student 0 score is 40 and grade is C
Student 1 score is 55 and grade is B
etc. to 4 students.
public class Lab_7_1{
public static void main(String[] args){
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.print("Enter the number of students: ");
int n1=input.nextInt();
int [] number=new int[n1];
System.out.print("Enter "+n1+" Scores: ");
String s1=input.next();
}
}
Try something like this:
public class Lab_7_1{
public static void main(String[] args){
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.print("Enter the number of students: ");
int n1=input.nextInt();
int [] number=new int[n1];
System.out.print("Enter "+n1+" Scores: ");
for (int i = 0; i < number.length; i++) {
number[i]=input.nextInt();
int b=i+1;
System.out.println("Score "+b+": "+number[i]);
}
int best = number[0];
for (int i = 0; i < number.length; i++) {
if (number[i]>best) best = number[i];
}
System.out.println("The best score is: "+best);
for (int i = 0; i < number.length; i++) {
if(number[i]>=best-20 && number[i]<=best-10) System.out.println("For score "+number[i] +" you get B grade.");
if(number[i]>=best-30 && number[i]<=best-20) System.out.println("For score "+number[i] +" you get C grade.");
if(number[i]>=best-40 && number[i]<=best-30) System.out.println("For score "+number[i] +" you get D grade.");
}
}
}`
Next step (using a for loop):
for (int i = 0; i < n1; i++) {
number[i] = input.nextInt();
}
Now that you've learned how to write a for loop, you can loop through the numbers to find the highest number, then do it again to print the results.

How to use Java to calculate average from input?

I need a program that should add x numbers. The numbers should come from user input so I need some sort of loop. I have gotten as far as shown below, but I'm stuck since I have no idea how to add a new number without deleting the previous?
System.out.println("How many numbers to use?");
int number = keyboard.nextInt();
for (int i = 0; i<number ; i++) {
System.out.println("whats the number");
double first = keyboard.nextDouble();
}
If all you need is the average, you don't need to keep all the numbers you get from user input. Just keep one variable that holds their sum.
define the sum variable outside the loop (initialized to 0), and add to it each number you get from user input.
int number = keyboard.nextInt();
double sum = 0;
for (int i = 0; i<number ; i++)
{
System.out.println("whats the number");
sum += keyboard.nextDouble();
}
double average = sum / number;
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum = 0;
int num;
System.out.println("enter how many num");
num = sc.nextInt();
System.out.println("please enter " + num + " numbers");
for (int i = 0; i < num; i++) {
sum += sc.nextDouble();
}
double avg = sum / num;
System.out.println("Average of " + num + " numbers is:" + avg);
}
}

Categories