Scanner not working with while loop - java

Maybe my google-fu is just terrible, but I'm having a very hard time figuring out how to do this. I'm trying to get a scanner to read a string, add the inputs, and return a value. I feel like I am just missing something... for example, I'm not sure how to get a variable set to the first double in the scanner.
import java.util.Scanner;
public class adding {
public static double sum(Scanner input){
Scanner s=new Scanner (System.in);
double i = (s.nextDouble());
double sumAnswer = 0;
while (s.hasNext()){
sumAnswer = sumAnswer + i;
i = s.nextDouble();
}
return sumAnswer;
}
public static void main(String[] args){
System.out.println(sum(new Scanner("1.2 2.8 3.9")));
}
}

You don't really need an i variable.
And, as already mentioned, don't have 2 Scanner's.
public static double sum(Scanner input){
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer += input.nextDouble();
}
return sumAnswer;
}

You shouldn't be resetting the scanner after passing the input.
public class adding {
public static double sum(Scanner input){
double i = (input.nextDouble());
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer = sumAnswer + i;
i = input.nextDouble();
}
return sumAnswer;
}
That ought to work better for you, maybe. I could also be mixing something up there...

Related

Java class to replace print statement and scanner input

Good Evening All,
I need help writing a class that enables to write a code like:
int number = Utility.getInt("Enter an int", '>');
to replace something like:
System.out.println("Enter an int>");
Scanner scan = new Scanner(system.in);
int number = scan.nextInt();
Please find my solution below. I am not sure if I am understanding the prompt correctly, not sure if I need to use a Java pre-defined Utility class or if I just need to name the class Utility. Any help or tip would be greatly appreciated thanks!
public class Utility {
private int number;
public Auto setInt (int number){
return "Enter an int" + number;
if (number>0)
this.number = newNumber;
return this;
}
public int getInt(){
return newNumber;
}
}
Have you tried static methods like below ?
public class Utility {
public static Integer getInt(String message){
System.out.println(message);
Scanner scan = new Scanner(System.in);
Integer number = scan.nextInt();
return number;
}
}

Not able to resolve object error in bluej

getting error that variable not found. not able to figure out exact problem. tried resetting preferences also in bluej.
import java.util.*;
class Electricity
{
public void Initialization()
{
int omr = 0;
int nmr = 0;
int cr = 0;
int rent = 0;
double cost = 0.0;
double sc = 0.0;
}
public void input()
{
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
}
public void calculate()
{
cr = nmr - omr;
}
public static void main()
{
Scanner sc = new Scanner(System.in);
}
}
This is not error in bluej it's problem with the code
I'm guessing you are a student
The code is not working since variable only exist inside the method it was created in
You are trying to access variable defined in different methods.
Inside the input() method you trying to access variable that you defined in Initialization() method But it does not exist in input()
Jest to make this code work put all your code inside the main() method .
Or pass the method the variables they using from another method and of course you need to call those methods from main method but seems like you have some more learning to do to make the second option to work.
Good luck.
Somthing like that.
import java.util.Scanner; // Import the Scanner class
public class Main
{
static int calculate(int nmr, int omr)
{
int cr = nmr - omr;
return cr;
}
public static void main(String[] args)
{
int omr = 0;
int nmr = 0;
// int cr = 0;
// int rent = 0;
// double cost = 0.0;
// double sc = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter old meter reading");
omr = sc.nextInt();
System.out.println("Enter new meter reading");
nmr = sc.nextInt();
System.out.println("The resaults: " + calculate(nmr, omr));
}
}

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

Java: Calling variables of user input from one method to another

I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}
To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}

How to store a double in an array incrementally

this is my first post and I hope someone can help. I have been struggling for ages to understand the problem I have and it looks as though I have done everything right yet problem persists. I have written a simple account program and would like to store the new balance after each transaction into an array index. From printing out balance I can see that it is adding and subtracting properly, however it is updating every single array index with the new balance rather than each incremental index. Can anyone spot my mistake. Thank you for any help with this.
Richard
public class TestAppAccount {
public static void main(String args[]) {
int count = 0;
do {
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count++;
//Account1.printBalance2();
} while (count <= 100);
}
public class AppAccount {
public static double[] currentBalance = new double[100];
static Scanner keyboard = new Scanner(System.in);
static double balance;
static int transaction;
public static void transaction() {
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1) {
System.out.println("Enter an amount to add ");
double amount = keyboard.nextInt();
double newBalance = balance + amount;
balance = newBalance;
} else
{
System.out.println("Enter an amount to withdraw");
double amount = keyboard.nextInt();
double newBalance = balance - amount;
balance = newBalance;
}
}
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
public static void printBalance() {
System.out.println("Balance: " + balance);
System.out.println("Balance: " + currentBalance[3]);//testing by printing 3rd index
}
}
Your storeBalance() method is iterating through the entire array and updating the values. If you want to only update one value, you'll need to keep track of where you've written up to and only write to the location one after that.
e.g.
Instead of
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
try this:
static int lastStored = 0;
public static void storeBalance() {
currentBalance[lastStored++] = balance;
}
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
That for loop is setting every value in the array to the value of balance. If each index is supposed to be a different account I would suggest passing an index to each function.
The problem is here:
public static void storeBalance() {
for (int i = 0; i < currentBalance.length; i++) {
currentBalance[i] = balance;
}
}
That for-loop will step through every element in the array, one by one, and will overwrite each value with whatever the current balance is.
There are a couple of ways you could fix this. My first reaction would be to create a variable that tells you the next index to write to:
static int nextIndex = 0;
and then storeBalance() would look like this:
public static void storeBalance() {
currentBalance[nextIndex] = balance;
nextIndex++;
}
You issue is you do a for loop and update every single value. You just want to update once when storeBalance() is called. Keep track of i as a static variable:
static int i = 0;
Then do this:
public static void storeBalance() {
if(i >= currentbalance.length)
i = 0;//restart value so it doesnt do array out of bounds
currentbalance[i] = balance;//update a single value
i++;//increment for next call
}
Make sure you do the out of bounds check. That's what the other answers are forgetting to check. Of course this will over write old values, so you can choose to do something else (what ever seems fitting for your requirements).
Stop pretending that java is c.
Java is not c.
Java likes objects.
Use objects.
Avoid arrays.
Here is some code:
// start Main.java file
public class Main
{
public static void main(String args[])
{
int count = 0;
do
{
AppAccount.transaction();
AppAccount.storeBalance();
AppAccount.printBalance();
count += 1;
}
while (count <= 4);
}
}
// start AppAccount.java file
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AppAccount
{
private static List<Double> currentBalanceList = new ArrayList<Double>();
private static Scanner keyboard = new Scanner(System.in);
private static double runningBalance;
private static int transaction;
public static void printBalance()
{
System.out.println("Running Balance: " + runningBalance);
}
public static void storeBalance()
{
currentBalanceList.add(runningBalance);
}
public static void transaction()
{
double amount;
System.out.println(" Press 1 to add funds, 2 to withdraw ");
transaction = keyboard.nextInt();
if (transaction == 1)
{
System.out.println("Enter an amount to add ");
amount = keyboard.nextDouble();
runningBalance = runningBalance + amount;
}
else
{
System.out.println("Enter an amount to withdraw");
amount = keyboard.nextDouble();
runningBalance = runningBalance - amount;
}
}
}

Categories