Amend all values in an Arraylist - java

I have a lab for my Programming I class where we need to design a program that uses an ArrayList of resistances to calculate the total resistance of a parallel and series circuit. For the parallel circuit, I need to change every item in the ArrayList to its reciprocal (1/item). I got to this point and cannot seem to find why this is wrong and a possible way around it. Thanks.
**the error I get is "The method get(int) in the type ArrayList is not applicable for the arguments (double)" for the line " resistances = 1 / resistances.get(index);" **
-businesslogic class-
import java.util.ArrayList;
/**
* The class Circuit gathers the resistances of a user-defined number of
* resistors for a user-defined type of circuit and displays the total
* resistance of the circuit for the main method of the Presentation class.
*/
public class Circuit {
private double arrayListSize;
public double n;
public double sum;
public double finalSum;
public ArrayList<Double> resistances = new ArrayList<Double>();
/**
* #param initialPop
* user-defined initial population
*/
public final void setArraySize(final double alSize) {
arrayListSize = alSize;
}
public final double getArraySize() {
return arrayListSize;
}
public final void setResistors(double alResistances) {
for (n = 0; n < getArraySize(); n++) {
resistances.add(alResistances);
}
}
public ArrayList<Double> getResistors() {
return resistances;
}
public final void setPResistance(ArrayList<Double> resistances) {
for (double index : resistances) {
resistances = 1 / resistances.get(index);
}
sum = 0;
for (double i : resistances) {
sum =sum + i;
}
double finalSum = 1 / sum;
}
public final double getPResistance() {
return finalSum;
}
}
-presentation class-
import java.util.Scanner;
/**
* The Class Presentation
*/
public class Presentation {
/**
* The main class uses the Circuit class and user input
* to calculate the total resistance of a circuit.
*
* #param args
* command line arguments
*/
public static void main(final String[] args) {
Scanner keyboard = new Scanner(System.in);
Circuit resistanceTotal = new Circuit();
System.out.println("This program will calculate the"
+ " total resistance of either a parallel or "
+ " a series circuit.\n");
System.out.println("Would you like to calculate the"
+ " resistance of a parallel circuit (1) or a"
+ " series circuit (2)?");
int userChoice = keyboard.nextInt();
System.out.println("How many resistors are there in the circuit?");
resistanceTotal.setArraySize(keyboard.nextDouble());
System.out.println("Enter resistance of resistor #" + (resistanceTotal.n + 1));
resistanceTotal.setResistors(keyboard.nextDouble());
resistanceTotal.getResistors();
if (userChoice == 1) {
resistanceTotal.setPResistance(resistanceTotal.getResistors());
resistanceTotal.getPResistance();
}
if (userChoice != 1 & userChoice != 2) {
System.out.println("You must enter 1 or 2!!!");
}
keyboard.close();
}
}

Your error is in this the setPResistance method. The method arrayList.get(i) takes a int value as a parameter, and you passed it the actual value of the position, which is a double.
To replace each item in the arraylist to its reciprocal, change the method like so:
public final void setPResistance(ArrayList<Double> resistances) {
for (int c = 0; c < resistances.size(); c++) {
resistances.set(c, 1/resistances.get(c));
}
}
Java docs on the set(int index, Double element) method:
Replaces the element at the specified position in this list with the
specified element.

Related

Illegal start of expression when making class for module (java)

I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...

Compare to variable from other class

I tried so hard but I couldn't get this to work. My method "guess" in class "Game" should compare the parameter "someInt" with the variable "x" from the class "Number". I would really appreciate any help, I have to get this done this evening. This is what I got, so far:
public class Number
{
private int x;
/**
* Constructor for class Number.
* This constructor assigns x to a new random
* number between 1 and 100
*/
public Number()
{
// The following lines creates a random number
// between 1 and 100 and assigns it to x
java.util.Random random = new java.util.Random();
x = random.nextInt(100) + 1;
}
public int getNumber(){
return x;
}
}
And my other class:
public class Game
{
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < x){
System.out.println("Your guess is too small");
}
else if (someInt > x) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
Here is a modified version
public class Game
{
private Number number;
/**
* This constructor should initialize the filled number
*/
public Game() {
this.number = new Number();
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < number.getNumber()){
System.out.println("Your guess is too small");
}
else if (someInt > number.getNumber()) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
On the other hand, you shouldn't use classes with the same names as in java.lang, as Number. It's distracting, making your code hard-readable and bug-genic.
The problems were:
Number.getNumber() does not take arguments, you provided one
You created a local object number1 while you should be operating on number.
In guess(), you used x, instead, Number.getNumber() should be used.
I recommend renaming Number to something not causing name clashes with java.lang.Number.
You have number1.getNumber(x); , but getNumber in your number class has no arguments.
In your getNumber method you have a return of x. You need to handle it in game like:
int numberToCompare; (declare below private Number number)
number1.getNumber(x); must be numberToCompare = number1.getNumber();
then you need to compare someint with numberToCompare.
this here is wrong:
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
because Number.getNumber() takes no param and must return an int (it is a GETTER)...
maybe you meant to do:
public class Game {
private int x;
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
this.x = number1.getNumber();
}

DataSorter.java:18: error: cannot find symbol

I've been attempting to work on a program for my AP java class and I've run in an issue where I have everything declared, it looks like everything has access to one another where i need it and my colleagues don't know either; here's what i have:
import java.util.Scanner;
/**
This is a test class for DataSet.
*/
public class DataSorter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter three numbers:");
double num1 = in.nextDouble();
double num2 = in.nextDouble();
double num3 = in.nextDouble();
DataSorter sorter = new DataSorter();
System.out.println("The inputs in sorted order are:\n" + sorter.getSmallest() + "\n" + sorter.getMiddle() + "\n" + sorter.getLargest());
}
}
Here's class 2
/**
This class finds the smallest, middle, and largest of
three numbers.
*/
public class DataSet
{
/**
Constructs a data set that processes three numbers.
#param num1 the first number to sort
#param num2 the second number to sort
#param num3 the third number to sort
*/
public DataSet(double num1, double num2, double num3)
{
num1 = dub1;
num2 = dub2;
num3 = dub3;
}
/**
Gets the smallest number in the data set.
#return smallest the smallest of three numbers
*/
public double getSmallest()
{
double smallest = dub1;
if(dub2 < smallest)
smallest = dub2;
if(dub3 < smallest)
smallest = dub3;
return smallest;
}
/**
Gets the largest number in the data set.
#return largest the largest of three numbers
*/
public double getLargest()
{
double largest = dub1;
if(dub2 > largest)
largest = dub2;
if(dub3 > largest)
largest = dub3;
return largest;
}
/**
Gets the middle number in the data set.
#retu rn mi ddl e the middle number of three numbers
*/
public double getMiddle()
{
double middle = 0;
middle = dub1 + dub2 + dub3 - getLargest() - getSmallest();
return middle;
}
private double dub1;
private double dub2;
private double dub3;
}
sorter is an object of class DataSorter. but it does not have methods getSmallest. its present in class2 (dataset)
you should make sorter object of Datase
DataSet sorter = new DataSet(num3, num3, num3);

Draw A Diamond, A Box, And A Vertical Line With While & For Loops, AND Switch Statements-Java

I wrestled with this for a couple of weeks now, and just can't figure this out. My assignment is to ask the user to input a number less than 20. If the input is 5,11, or 15, the program is to draw a diamond. 3,9, or 17 it draws a box(just the outline). Anything else, it is to draw a vertical line of the same height as the input number. We had to write a method for the diamond that accepts an integer & returns a string(using a while loop), the same for the box(using a for loop) & vertical line. Those methods do not output. We are also required to use the drawHLine method the teacher created.
Then write a method asking for the input, which used a class called IO that we'd previously written for another assignment. We are to use a switch statement to determine which shape to draw.
My problem is that, I've worked out the methods which create the top half of my diamond, as well as the one for the box. But I cannot figure out how to then draw the bottom half.
Here's my working IO class:
/*
* This is a stand alone utility package to be used over again.
*/
package util;
/**
*
* #author Michael
*/
import java.awt.Font;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/* getInput asks for input from GUI, then outputs to a Dialog box.
*getConsoleInput uses the console to ask for input, then outputs
*it to the console.
*/
public class IO {
public static Scanner getInput( String prompt){
String s = JOptionPane.showInputDialog(prompt);
return new Scanner(s);
}
/* Defines the getConsoleInput method, which requests input from the
*console, then returns output through the console.
*/
public static Scanner getConsoleInput(String prompt ){
System.out.println(prompt);
Scanner input = new Scanner(System.in);
return input;
}
/*Defines the showMessage method, which outputs to a Dialog Box
*/
public static void showMessage(String s){
System.out.println(s);
JOptionPane.showMessageDialog( null, s);
}
/*Defines the overloaded showMessage method, which outputs to a Dialog Box,
but changes the text from whatever is initially the default.
*/
public static void showMessage(String output,String title ) {
System.out.println(output);
JTextArea jta = new JTextArea(title);
jta.setFont(
new Font("Verdana",
Font.BOLD, 14));
JOptionPane.showMessageDialog( null, jta);
}
}
And here is what I have so far of the program:
/*
* The purpose of this program is to ask the user to enter a positive odd
* number less than 20, then depending on the number entered, draw either
* a diamond (outline only), a box(outline only), or a verticle line.
*/
/**
*
* #author Michael Davis
*/
import util.IO;
import java.util.*;
import javax.swing.*;
public class Assignment5 {
public static String drawHLine(int n, char ch) {
String result = "";
for (int i = 0; i < n; i++) {
result += ch;
}
return result;
}
public static String drawDiamond(int n) {
String result = "";
int x = 1;
int y = 1;
int spaces = n / 2;
while (x <= n) {
result += drawHLine(spaces, ' ')
+ drawHLine(x, '*') + "\n";
x += 2;
spaces--;
}
while ( y>=1){
result += drawHLine(spaces, ' ') +
drawHLine(y, '*') + "\n";
y -=2;
spaces++;
return result;
}
}
/*
public static String drawBox(int n) {
String result = "";
int x = 0;
while (x <= n) {
for (int j = 0; j < n; j++) {
if (j == 0 || x == 0) {
result += " *";
}
}
result += "\n";
x++;
}
return result;
}
*/
public static void main(String[] args) {
Scanner input = IO.getInput("Please enter a number less than 20");
int choice = input.nextInt();
switch (choice) {
case 5:
case 11:
case 15:
IO.showMessage(drawDiamond(choice) , "Diamond");
break;
/*
case 3:
case 9:
case 17:
IO.showMessage(drawBox(choice), "Box");
break;
*/
}
System.exit(0);
}
}
Your code doesn't work because you initialize the y variable to 1. Since this variable describes the remaining width of a line in the bottom half of the diamond, its initial value needs to be the width of the diamond.

Java: Running total for a loop and error: missing return statement

I am still new to Java and I can't figure out how to get it to keep a running total. Any suggestions on what I should look up would be awesome. Thank you for your time.
import javax.swing.*;
public class OrderingProducts2
{
public static double main(String[] args)
{
// Number of products
final int NUMBER_OF_PRODUCTS = 5;
//all of the valid values
int[] validValues = {1, 2, 3, 4, 5};
//prices that coralate with the values
double[] prices = {2.98, 4.50, 9.98, 4.49, 6.87};
//Starting total price of order
double total = 0.00;
//Sring for chosing a product to order
String strProducts;
int productOrdered;
//Starting price of unnamed product
double productPrice = 0.00;
//boolean used to validate product
boolean validProduct = false;
//User input of product number
strProducts = JOptionPane.showInputDialog(null,"Enter the product number you want to order or done");
//product number being converted to an integer
productOrdered = Integer.parseInt(strProducts);
//string for getting the quanity
while(productOrdered > -1)
{
String strQuanity;
int productQuanity;
//user input of quanity
strQuanity = JOptionPane.showInputDialog(null,"Enter the amount of product " + strProducts);
//conversion of the quanity to an integer
productQuanity = Integer.parseInt(strQuanity);
//validation and totaling of the price of order
for(int x = 0; x < NUMBER_OF_PRODUCTS; ++x)
{
if(productOrdered == validValues[x])
{
validProduct = true;
productPrice = prices[x];
total = productPrice * productQuanity;
}
}
}
//if there awas a valid out put this message will show
if (validProduct)
JOptionPane.showMessageDialog(null, "The price for product " + productOrdered + " is $" + productPrice + ". The price for your ordered item/items so far is $" + total);
//if output was not valid this message will show
else
JOptionPane.showMessageDialog(null,"Sorry1 - invalid product entered");
Why is the return type for main double?
It should be public static void main(String[] args)
public static double main(String[] args)
according to j.l.s 12.1.4:Invoke Test.main
Java's main() method to execute should be: declared public, static,
and void. It must specify a formal parameter (ยง8.4.1) whose declared
type is array of String. Therefore, either of the following
declarations is acceptable:
So either: public static void main(String[] args)
or, public static void main(String... args)
Again, assuming that you are using public static double main() method then, you must a return double type value:
This is specified in jls-8.4.7 Method body:
If a method is declared to have a return type, then a compile-time
error occurs if the body of the method can complete normally. In other
words, a method with a return type must return only by using a return
statement that provides a value return; it is not allowed to "drop off
the end of its body".
while(productOrdered > -1)
{
// your code
}
I don't see you have updated(decrement or some other opearation) the productOrdered which might cause it to have a value -1. be careful about it. I may want it to be checked with if-else condition.
There are two immediate issues, but it's difficult to know which one is wrong...(or less correct)...
public static double main(String[] args)
Is wrong for one of two reasons. If this is suppose to be you applications main entry point, then it should read...
public static void main(String[] args)
Otherwise Java won't be able to run your application.
If it's not (and it's just some static method you want to run), then you it should have a return statement before it exists. In which case, it's unlikely that you'll be able to run the class until you either provide a implementation of public static double main(String[] args) somewhere to call it...
For example...
public static void main(String[] args) {
OrderingProducts2.main(args);
}
Updated
In order to generate a running tally, you need to provide some kind of exit value from your loop that the user is capable of entering, in you code you're used productOrdered, but you never change that value within the while loop.
A better solution might be to validate the productOrdered before you enter the loop and use productQuanity as the exit value.
In you main loop, you are also not incrementing the total, but you are simply setting it's value...
total = productPrice * productQuanity;
Instead, you could use something like...
total += productPrice * productQuanity;
While will increment the total on each loop...
And finally, a runnable example...
// Number of products
final int NUMBER_OF_PRODUCTS = 5;
//all of the valid values
int[] validValues = {1, 2, 3, 4, 5};
//prices that coralate with the values
double[] prices = {2.98, 4.50, 9.98, 4.49, 6.87};
//Starting total price of order
double total = 0.00;
//Sring for chosing a product to order
String strProducts;
int productOrdered;
//Starting price of unnamed product
double productPrice = 0.00;
//boolean used to validate product
boolean validProduct = false;
//User input of product number
strProducts = JOptionPane.showInputDialog(null, "Enter the product number you want to order or done");
//product number being converted to an integer
productOrdered = Integer.parseInt(strProducts);
for (int x = 0; x < NUMBER_OF_PRODUCTS; ++x) {
if (productOrdered == validValues[x]) {
validProduct = true;
productPrice = prices[x];
}
}
if (validProduct) {
int productQuanity = -1;
do {
//string for getting the quanity
String strQuanity;
//user input of quanity
strQuanity = JOptionPane.showInputDialog(null, "Enter the amount of product " + strProducts);
//conversion of the quanity to an integer
productQuanity = Integer.parseInt(strQuanity);
//validation and totaling of the price of order
if (productQuanity > -1) {
for (int x = 0; x < NUMBER_OF_PRODUCTS; ++x) {
if (productOrdered == validValues[x]) {
validProduct = true;
productPrice = prices[x];
total += productPrice * productQuanity;
}
}
}
} while (productQuanity > -1);
JOptionPane.showMessageDialog(null, "The price for product " + productOrdered + " is $" + productPrice + ". The price for your ordered item/items so far is $" + total);
} else {
JOptionPane.showMessageDialog(null, "Sorry1 - invalid product entered");
}
Your main method should be
public static void main(String[] args){
//no return values
}
The main method should have the following signature, else you would not have an entry point of for your Java application.
public static void main(String[] args) // return type is void and not double
And also, you don't need a while there, it'll just be an infinite loop. Replace it with an if.
if (productOrdered > -1) {

Categories