So the challenge is to prompt the user to enter an integer value "count". Next
prompt them to enter "count" more values. Then square each value entered and add it to a main
value sum.Then display the sum of the square of all the numbers entered.
An example of the build output is like :
Please enter an integer value: 3
Please enter 3 numeric values:
7 8 3.5
The sum of the squares of each of these numbers is: 125.25
I'm still new to learning code, so I'm a bit lost at how to square multiple values on a single user input and also totaling them up. Can anyone offer some help?
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
sum_squares();
}
public static void sum_squares(){
Scanner in = new Scanner(System.in);
System.out.println ("Please enter an integer value:");
int count = in.nextInt();
System.out.println ("Please enter" + count + "more values:");
int square = in.nextInt();
}
}
You need to add a for-loop after:
System.out.println ("Please enter" + count + "more values:");
The for-loop should run for count times, and each time the loop is run, it should ask the user for an input. You can then take that input and square it (remember - squaring is as easy as multiplying a number by itself! 2 * 2 = 4, or 2-squared) Once you have the squared number, add it to a sum variable which you will have created before the for-loop. Then just print out the sum after the for-loop.
Here is a great tutorial on for-loops!
Related
Now we are learning about while loops - here is the challenge. "the program should repeatedly prompts the user to enter a number. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters something that is not an integer. When the user has finished, print the number of entries the user has typed and their sum."
"A sample interaction with this program might look like this:
Program: Enter an integer to continue or a non-integer value to finish. Then press return.
User: 2
Program: Enter an integer to continue or a non-integer value to finish. Then press return.
User: 6
Program: Enter an integer to continue or a non-integer value to finish. Then press return.
User: 89
Program: Enter an integer to continue or a non-integer value to finish. Then press return.
User: q
Program: You entered 3 integers. The sum of your entries is 97."
Here's what I have so far.
import java.util.Scanner;
public class InputSequence
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int sum = 0;
int total = 0;
while (scan.hasNextInt())
{
scan.next();
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int input = scan.nextInt();
sum = input + input;
total = total + 1;
}
System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
}
}
I'm just a bit confused because my interaction seems to skip the system.out.println every 2nd time in the while loop and then doesn't count the first input into the total. I believe the sum also doesn't always calculate correctly. Also, if I input a lot of integers then a non-integer to end the program I will receive an error rather than the end message. However, let's say I put in two integers then a string, I will get the end message.
Your problem is in the usage in scan.next() that can be removed and should show the System.out.println correctly.
.next() method is a generic method of nextInt() which returns a String instead.
Another thing you can do is to switch from a while loop to do while to prevent you from repeating this line twice:
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
an example would be:
Scanner scan = new Scanner(System.in);
int sum = 0;
int total = 0;
do {
System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
int input = scan.nextInt();
sum = sum + input;
total = total + 1;
} while (scan.hasNextInt());
System.out.println ("You entered " + total + " integers. The sum of your entries is " + sum);
}
Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number
import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.
Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.
How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.
Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.
In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.
To fix this, don't progress your program until your input is valid using a while loop, like this:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}
You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}
Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers typed in by the user. You may assume the user enters a valid number greater than 0 for the number of numbers to read. Here is an example dialogue:
How many numbers do you want to enter? 4
Number 1: 5
Number 2: 11
Number 3: -2
Number 4: 3
Smallest = -2
Largest = 11
This is what i have done but i am unable to get the smallest and largest output.
import java.util.*;
public class smallestLargest{
public static void main(String[] args){
System.out.print("How many numbers do you want to enter? ");
Scanner sc=new Scanner(System.in);
int count=sc.nextInt();
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
for(int i=1;i<=count;i++){
System.out.println("Number" + i + ": ");
int nextNumber=sc.nextInt();
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
}
System.out.println("Smallest= "+ smallest);
System.out.println("Largest= "+ largest);
}
}
This is the problem:
if(nextNumber<smallest){
smallest+=nextNumber;
}
else if(nextNumber<largest){
largest+=nextNumber;
}
That doesn't do what you want at all.
I'm not going to give you the solution, but think about it - just do one of them at a time. Let's start with "smallest".
If our current smallest number is 5, and someone enters 2, what should the new smallest number be? Why?
If our current smallest number is 5, and someone enters 10, what should the new smallest number be? Why?
Work that out, then apply the same thought process to "largest number".
Don't use "else if", because on the first loop, the number will pass both tests - i.e. it will be the smallest AND the largest, also don't use "+=", just "=" and change the "largest". So something like:
if(nextNumber<smallest)
smallest=nextNumber;
if(nextNumber>largest)
largest=nextNumber;
Little bit 'I am lazy' solution:
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt())
{
numbers.add(sc.nextInt());
}
System.out.println("Smallest= " + Collections.min(numbers));
System.out.println("Largest= " + Collections.max(numbers));