Polynomial Code 22 - java

I am trying to write a program to allow the user to input two polynomials with different degrees, I believe that my do while loop is incorrect and I cannot figure out how to let the user input the second polynomial.
{
int i, coef, x, deg;
double total=0.0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Degree");
deg=sc.nextInt();
System.out.println("Enter x");
x=sc.nextInt();
do
{
for (i=0; i<=deg; i++)
{
System.out.println("Enter Coefficent for " +i);
coef=sc.nextInt();
total=total+coef*Math.pow(x,i);
}
}
while ( deg != 0);

Related

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

How do you store integer into a variable and computeAvg in java?

I am trying to write a Java program that:
In the main method, prompt the user for an integer number.
Store the number in a variable called inputNum.
Pass the inputNum to a method called computeAvg.
In computeAvg, prompt the user to input double values as many times as inputNum. computeAvg method should calculate and return the average of real numbers that user entered.
Print the result in your main method.
This is my code
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
computeAvg();
}
public static void computeAvg() {
System.out.println(inputnum);
System.out.println("Enter double values as inputnum ");
int y;
y=keyboard.nextInt();
}
}
There are several changes to be done in your code:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a integer? ");
int x;
x = keyboard.nextInt();
int inputnum=x;
System.out.println("The average is"+computeAvg(inputnum));
}
public static double computeAvg(int y)
{
double[] arr = new double[y];
System.out.println(y);
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
double sum = 0;
for(double a:arr){
sum +=a;
}
System.out.println(sum);
double average = sum/arr.length;
return average;
}
First one is that the value you first taken as the user input must be passed to the method. Here I done it in computeAvg(inputnum) And expect this method to return a double value.
Second one is You should declare the method to return a value void means no return. change it to double
public static double computeAvg(int y)
take the parameter from the main method (value you taken from the user.)
If you need to store multiple values better solutions is array.(There are many methods bust for a beginner stick to arrays) crate a double array to take multiple double values.
double[] arr = new double[y];
next loop your code for the number of times the user input and take the double values.
for (int i = 0; i < y; i++) {
System.out.println("Enter double values ");
arr[i] = keyboard.nextDouble();
}
next create a double value sum and get the addition and the divide it to get the average (another double value).
for(double a:arr){
sum +=a;
}
Finally return the average to the main method where it prints.
I used static Scanner keyboard = new Scanner(System.in); because I used the same scanner in both methods.
Feel free to ask any question regarding the code.
I hope the comments in the code are self explanatory for what the problem is asking and how the code works:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer? ");
// here you are asking for the number of double numbers that will be
// entered
int inputnum = keyboard.nextInt(); // asking for the int input (varibale
// is stored in inputnum)
System.out.println("Average for all " + inputnum + " numbers is: "
+ computeAvg(inputnum));
}
public static double computeAvg(int inputnum) {
Scanner keyboard = new Scanner(System.in);
double eachInput = 0.0;
double sumInputs = 0.0;
for (int counter = 1; counter <= inputnum; counter++) {
System.out.println("Please enter a double as input #" + counter
+ ": ");
eachInput = keyboard.nextDouble(); // asking for double input
sumInputs += eachInput; // adding up each input
}
// calculating and returning average
return sumInputs / (double) inputnum;
}

Using a for loop to read ONLY 5 numbers and average them. JAVA

Really having issues with this program I'm making. I've searched this site and a few others, although have yet to find a solution. It may look like I'm just soliciting help but I truly am stuck. I am to make a program that reads in 5 numbers from the user and average those numbers. My extent of knowledge of Java is the Scanner class and for loops, yet haven't used while loops yet. Here is the very poorly written code:
public class Average5
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
num = sc.nextInt();
}
I honestly have no clue what to do. More or less self taught.
public class Average5 {
public static void main(String args[]) {
int numlenngth = 5;
double total = 0;
Scanner sc = new Scanner(System.in);
for (int num1 = 0; num1 < numlenngth; num1++) {
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : " + (total / numlenngth));
}
}
output >>
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 1
Please enter a number: 2
Average : 1.2
For calculating exact average, you need to take double(sum) instead of int and add(sum) everytime with the user value.
public class Average5
{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to enter for calculating average: ");
int totalCount = sc.nextInt();
double sum=0;
for(int i= 0; i<totalCount; i++)
{
System.out.print("Please enter a number: ");
sum += sc.nextDouble();
}
System.out.println("Average of number is"+(sum/totalCount));
}
This is almost the same as the others posted, but it is limited to entering only 5 numbers and it takes care of possibly resulting floating number in the final division:
import java.util.Scanner;
public class Average5 {
private static final int TOTAL = 5;
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.format("You have to enter %d numbers now.\n", TOTAL);
for (int cnt = 1; cnt <= TOTAL; cnt++) {
System.out.format("Please enter number %d of %d: ", cnt, TOTAL);
sum += scanner.nextInt();
}
System.out.format("The average is %f.\n", sum / TOTAL);
scanner.close();
}
}
Here you can use the array to store the numbers:
public class Average5 {
private static final int MAX = 5;
public static void main(String[] args) {
int[] numbers = new int[MAX];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < MAX; i++) {
System.out.println("Please type the number");
numbers[i] = sc.nextInt();
}
float average = getAverage(numbers);
System.out.println("The average of the five numbers: " + average);
}
public static float getAverage(int[] arg0) {
int sum = 0;
float Ret = 0.0f;
if(arg0 != null) {
for(int i = 0; i < MAX; i++) {
sum += arg0[i];
Ret = sum / MAX;
}
return Ret;
}
}
This is not the only way to slove this problem.
int num = 0;
float total = 0f;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number: ");
num = sc.nextInt();
for(int num1 = 0; num1 <= num; num1++)
{
System.out.print("Please enter a number: ");
total += sc.nextInt();
}
System.out.println("Average : "+(total/num));

I need to find specific variables that the user has inputted however I don't comprehend how

Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}

How do I create a list of user inputs?

I am coding in Java and I have to create a program that accepts user input, which I have done. But I am confused as to what statement I can use to list those integer input by the user.
This is what I have so far:
//Biker's Journey Program
import java.util.Scanner;
public class lab2
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in);
int w;
int x;
int y;
int z;
int result;
System.out.print("Please enter the first day's traveled miles: ");
w = input.nextInt();
System.out.print("Please enter the second day's traveled miles: ");
x = input.nextInt();
System.out.print("Please enter the third day's traveled miles: ");
y = input.nextInt();
System.out.print("Please enter the last day's traveled miles: ");
z = input.nextInt();
System.out.print("The number of miles traveled was: ");
System.out.println()
result = (w + x + y + z) / 4;
System.out.printf("The average miles per day traveled is %d\n", result);
}
}
And this segment of code does the computing, I just can not figure out how to get the integers listed like this this picture: http://imgur.com/KFNkWEd
System.out.printf("The number of miles traveled each day was: %d %d %d %d", w,x,y,z);

Categories

Resources