Java: Saving User Input to be Calculated in a Loop - java

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?

Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);

You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}

You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}

// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Related

why can int not be deferenced?

I'm writing a while loop program and this problem keeps staying here and I'm not sure how to fix it. Keeps displaying "int cannot be dereferenced". I have done a ton of research on this problem and I don't know what am I doing wrong: read on google, read on StackOverflow and so on, but I don't know what to do. Tried the parsing technique but kept saying "scanner cannot convert string to int" Here is my code, any help would be appreciated. I could have declared the variable in the if and else if conditions, but I would like to keep track of what I am doing and I believe it's better to not repeat codes. (such as print out statement)
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner Data = new Scanner (System.in);
final int goldplated = 100, fourteen = 500, eighteen = 1000;
int total = 0, count = 1, size = 0;
String GetInfo = "";
System.out.println("How many times do you want to purchase:");
int EnterData = Data.nextInt();
while(count<=EnterData){
System.out.println("What Kind of Chain do you want to buy? Below are the list of options: \n 1 - gold plated \n 2 - 14k gold \n 3 - 18k gold");
//GetInfo = Data.next();
if (Data.equals("1")||Data.equals("gold plated")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * goldplated;
}else if(Data.equals("2")||Data.equals("14k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * fourteen;
}else if(Data.equals("3")||Data.equals("18k gold")){
System.out.println("Please specify the length of the chain.");
size.nextInt();
total = size * eighteen;
}else{
System.out.println("Invalid operation");
} count++;
total+= size.nextInt();
System.out.println("This is your price: " + total);
}
}
}
nextInt() is a method in the Scanner class. So when you write something.nextInt(), the something part will have to be a Scanner object. And in your case, you've got a Scanner object, which you've called Data (not the best name for it, but never mind).
If you write Data.nextInt(), your program will wait for the user to type in a number, and return that number. That's what you want, but you'll want a variable to assign that number to, so that you can use it. That variable is size. So every time you've written size.nextInt(); in your program, what you actually need to write instead is size = Data.nextInt(); - that is, call the method on the Data object, and assign the result to the size variable.

Why is there no output from the While loop in my code, despite everything else working?

I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.

Need help Spotting A logic error in my program (prime numbers) / understanding output

New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.

Difficulty exiting "user input" method called in main Java

I am trying to bring in some numerical values by way of Scanner(System.in). I am calling a class with my method from main and having a difficult time exiting the method, my questions are looping.
I am sure this is a simple issue but I am having a heck of a time finding a solution.
Here is the method:
public static Object userInput(double nutWidth, double lastFretWidth, double scaleLength, int numFrets) {
boolean dataCheck = true;
try {
while (dataCheck == true) {
System.out.println("What is the width at the nut?");
NutWidth = key.nextDouble();
System.out.println("What is the width at the last fret?");
LastFretWidth = key.nextDouble();
System.out.println("What is the scale length?");
ScaleLength = key.nextDouble();
System.out.println("How many frets will your guitar have?");
NumFrets = key.nextInt();
dataCheck = false;
}
} catch (InputMismatchException e) {
System.out.println("Enter a integer.");
key.nextInt();
}
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
}
Here is my main:
public static void main(String[] args) {
FingerBoard.userInput(0, 0, 0, 0);
FingerBoard.UserData();
}
Any help is greatly appreciated-Mike
You have written an infinite recursion. The line
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
will call the same method again after finishing the previous method. It looks to me like you want to store the values in a data structure and return that, which would require calling a constructor something like this:
return new UserInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
You would have to write the data structure UserInput yourself. If you haven't gotten to writing classes and data structures yet, you probably want your variables to be static fields. If you are doing that, change the return type to be void and remove the return statement entirely.
Additional comments not related to your problem. You don't need the arguments to your method. They are never used. You probably also want to put the try/catch inside of the while loop. That way an invalid input will prompt for new input, rather than setting things to 0.

Java- Saving score in a game

I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());

Categories

Resources