I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}
Related
I'm very new to coding, and one of my projects was to create a program that uses a while loop to ask a user for test grades and find the average. The problem I have is that when it asks for the first grade, my instructor wants it to also print out "Enter -1 when you're finished" along with the first grade only. He wants the results to look something like this.
Test grade1? (Enter -1 when you are finished): random grade
Test grade2? random grade
Test Grade3? random grade
The average of your test grades is: average of all grades
Currently, I have the first grade as a separate line of code that asks the user and it is not in the loop. Is there any way to combine it into the loop and still have it to ask "Enter -1 when you're finished" but for only the first test grade?
P.s Sorry if my code is very messy I'm still not very good at it.
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Test grade 1? (Enter -1 when you're finished): ");
int grade1 = scan.nextInt();
int i = 2;
int testCounter = 1;
int sum = 0;
boolean flag = true;
while(flag) {
System.out.print("Test grade " + i + "? ");
int grades = scan.nextInt();
if (grades == -1){
flag = false;
break;
}
sum = grade1 + grades;
grade1 = sum;
i++;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double)sum/testCounter);
}
}
You can just check with an if statement whether it's the first test and display the additional message if that's the case.
Also you can get rid of the i variable and use testCounter in it's place. You also don't need the flag, just using break is enough.
At the end of the loop the testCounter will be off by one so you have to decrement by one when calculating the average ((testCounter - 1)).
import java.util.Scanner;
public class U4D3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCounter = 1;
int sum = 0;
while (true) {
System.out.print("Test grade " + testCounter + "? ");
if (testCounter == 1)
System.out.print("(Enter -1 when you're finished): ");
int grade = scan.nextInt();
if (grade == -1) {
break;
}
sum += grade;
testCounter++;
}
System.out.println("The averages of your test grades is: " + (double) sum / (testCounter - 1));
}
}
I am learning Java and am having a very simple problem.
How to print the final sum from a while loop?
if I enter integers 10 10 40
the output I get is
10
20
60
but am only trying to get the final 60.
This answer can also relate to printing the final anything in a while loop as I just can't seem to get this.
my sample code below...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
System.out.println("The Sum is: " + total);
}
}
Your main problem is that you have put the print statement inside the loop.
Also, in.hasNextDouble() doesn't make sense for input from the keyboard; it is useful when you are reading data from a file or a Scanner for some string. You can use an infinite loop (e.g. while(true){...}) and break it when there is no input from the user.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up, press Enter without any input to exit: ");
double total = 0;
while (true) {
String input = in.nextLine();
if (input.isBlank()) {
break;
}
total += Double.parseDouble(input);
}
System.out.println("The Sum is: " + total);
}
}
A sample run:
Enter a sequence of numbers to sum up, press Enter without any input to exit:
10
20
30
The Sum is: 60.0
A demo of a Scanner for a string:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
}
Output:
The Sum is: 60.0
The problem lies in: System.out.println("The Sum is: " + total);
If you would like for only the final sum to be printed it needs to be outside of the while loop.
Please, print the total outside of the loop and it will work fine !
Code:
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of numbers to sum up: ");
double total = 0;
while (in.hasNextDouble()) {
double input = in.nextDouble();
total = total + input;
}
System.out.println("The Sum is: " + total);
}
I've been having issues catching non numbers.
I tried try / catch but I can't grasp a hold of it. If anything I get it to catch non numbers, but doesn't let the user try entering again... It just stops my code completely.
Here is my code:
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner angle1 = new Scanner(System.in); // Reading from System.in
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
Scanner angel2 = new Scanner(System.in);
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
Scanner angel3 = new Scanner(System.in);
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
//this is just telling how much degrees the user had in total if they didnt match up to triangle standards
This should get you started.
package triangle;
import java.util.Scanner;
public class triangle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\n");
System.out.println("this automated program will tell you if the angle you entered is isoceles, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner s = new Scanner(System.in); // Reading from System.in
String line;
int [] angles = new int [3];
int count = 0;
do {
System.out.print("Enter angle degree number " + (count+1) + ": ");
line = s.nextLine();
while (true ) {
try {
angles[count] = Integer.parseInt(line);
System.out.println("You entered " + angles[count]);
count++;
break;
} catch (NumberFormatException e ) {
System.out.println("Invalid number: try again: ");
line = s.nextLine();
}
}
} while (count < 3);
}
}
You have a simple issue.. You just use one Scanner for the code in main method.
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] argc){
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
Scanner angle1 = new Scanner(System.in);
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
I'm getting the prompt to enter an integer but nothing after that. Can someone tell me why my results are not printing?
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
if (x == z && y == y && z == x)
System.out.println(answer + " is a palindrome! ");
else
System.out.println(answer + " is not a palindrome");
}
}
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
Your code is waiting for 4 different inputs. If you input all 4, it will run - but something is clearly wrong with your logic.
As others mentioned, you are a) working with doubles and b) trying to read too many numbers:
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
// Read an int
int answer = 0;
try {
answer = input.nextInt();
}
catch (InputMismatchException ex) {
// Handle error
}
// Make sure it's 3 digits
if (answer < 100 || answer >= 1000) {
// Do something with bad input
}
else {
// Just need to check if first and third digits are equal.
// Get those values using integer math
int digit1 = answer / 100;
int digit3 = answer % 10;
if (digit1 == digit3) {
System.out.println(answer + " is a palindrome! ");
}
else {
System.out.println(answer + " is not a palindrome");
}
}
}
}
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
/*
OUTPUT:
Enter a string : MADAM
Entered string is a palindrome.
Enter a string : 15351
Entered string is a palindrome.
*/
You are using wrong logic here.If you want to check for palindrome, you should not use double.Hope this code helps!
So I am taking Java as part of math degree requirements and have stumbled on a problem with this code. Essentially the code is supposed to take in numbers from the user until they type a zero. It works fine as long as only numbers are entered. However if the user enters a letter or symbol the program gets an exception. Is there a simple way I can validate user input as a number without getting an exception?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
So I've tried the try/catch as you showed it. I'm still getting an exception with non numbers though. Entered the code as follows:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class SamsAdder {
public static void main(String[] args) {
double userInput = 1;
double sum = 0;
Scanner in = new Scanner(System.in);
while (userInput != 0) {
try {
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
} catch (InputMismatchException nfe) {
System.out.println("Invalid Number");
in.next();
}
}
in.close();
System.out.println("The sum of the numbers is " + sum + ".");
}
}