Java: Adding and Subtracting Digits Taken from a String - java

So the purpose of this program is to get the user to enter an integer that the program will recognize as a string. Then the program has to be able to recognize each of the numbers entered and manipulate them as follows. Digits are to be added together if the digits are the same or if the next digit is greater. Digits are to be subtracted if the next digit is smaller.
An example:
The input "234224" should output 13(2+3+4-2+2+4)
However my program gives an output of 17.
I don't know how to fix the problem. My problem is in my first if statement. When the second occurrence of "2" is read I want the program to subtract 2 from the output being calculated but instead it adds 2 because of how I coded the first if statement.
Could someone give me a solution using the same method I used if possible?
public class StringManipulation {
public static void main(String[] args) {
String userInt;
int total = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
userInt = input.nextLine();
for (int k = 0; k < userInt.length(); k++) {
int presentNum = userInt.charAt(k);
System.out.println(userInt.charAt(k));
if (presentNum == userInt.charAt(0)) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
} else if (presentNum >= userInt.charAt(k - 1)) {
total += Character.getNumericValue(presentNum);
System.out.println("counter currently at (adding)" + total);
} else if (presentNum < userInt.charAt(k - 1)) {
total -= Character.getNumericValue(presentNum);
System.out.println("counter currently at (subtracting)" + total);
}
}
System.out.println("Output= " + total);
input.close();
}
}

Your problem is with your initial check
if (presentNum == userInt.charAt(0))
in other words, you do stuff if the number you're looking at is the same as the first number. In this particular case, that condition kicks in when you encounter the 2 later in the string, and you end up adding it instead of subtracting it.
You probably wanted that condition to be
if (k == 0)

if (presentNum == userInt.charAt(0)) {
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
System.out.println("counter currently at (same)" + total);
}
Your problem lies here. The first digit is added to the sum regardless of the previous digit. That means the output changes from 13(2+3+4-2+2+4) to 17(2+3+4 +2 +2+4).
You should have something like
if (k==0){
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
}
for the first digit.

Try to change the first if condition, as follows
if (k==0) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
}
Because, at the first iteration you have only one operand and you don't have take the value at 0th index for the condition, rather than that just see whether is it the first index.

Related

How to expand a number to match another in Java

I'm given a number for example 319 and i need to write code that will break out a number to 3192310, for example. I'll try to explain how it needs to be done and what i've tried.
Explanation: (given two inputs: 319 and 3192310) So the program starts by appending 0 to 9 at the end of 319, and compares that fourth digit to the fourth digit in 3192310. In this case, that digit would be "2". At the line 3192, the program appends 0 to 9 at the end of 3192, and compares the fifth digit to the fifth digit in 3192310. In this case, that digit would be "3". the program continues until it reaches the end and a "bingo" string is appended to 3192310.
Here's an example of what the output should be:
319
3190
3191
31920
31921
31922
319230
3192310 bingo
3192311
3192312
3192313
3192314
3192315
3192316
3192317
3192318
3192319
319232
319233
319234
319235
319236
319237
319238
319239
31924
31925
31926
31927
31928
31929
3193
3194
3195
3196
3197
3198
3199
My attempt: So I had started by first taking the last 4 characters of the input from a JTextField and placing it in an array. Then I created a for loop with an if and else statement comparing the index of the for loop to the value of the array at a given index. If the index of the for loop matched the value of the array, called the funtion again (recursive function). See my code below:
public JTextArea banalysis(JTextField npaInput, JTextField rcInput, JTextField ccInput, JTextField lInput, JTextField breakoutInput, JTextField newRcInput){
//Store text field inputs into variables
String number=numberInput.getText();
String breakout=breakoutInput.getText();
int breakoutLength= breakout.length();
String breakoutNoNpa=breakout.substring(3,breakoutLength);
int[] breakoutArray=new int[breakoutNoNpa.length()];
for(int r=0;r<breakoutNoNpa.length();r++){
breakoutArray[r]=Integer.parseInt(breakoutNoNpa.substring(r,r+1));
}
this.recursivePrint(0,breakoutArray, number);
return rightOutputBText;
}
public void recursivePrint(int index, int[] breakoutArray, String number) {
//number=319 is a String
for (int i=0; i<=9;i++) {
if (i == breakoutArray[index]) {
index++;
number=(number+i);
recursivePrint(index, breakoutArray, number);
} else {
rightOutputBText.append( number + i + "\n");
}
}
}//end of recursivePrint method
But this is my output:
319
3190
3191
31920
31921
31922
319230
I've gone through my code and I get how I got the output, I'm just not sure how to change it. I feel lke I need some sort of nested for loop but I'm not sure. Can anyone help me out. Thanks
I figured it out. Your code was originally throwing an IndexOutOfBoundsException because index was not being checked against breakoutArray.length - 1. After I fixed the exception, with if((index < breakoutArray.length - 1) && i == breakoutArray[index]), I was getting the following wrong output:
3190
3191
31920
31921
31922
319230
3192310 bingo
3192311
3192312
3192313
3192314
3192315
3192316
3192317
3192318
3192319
3192312 <-- this should be 319232
3192313 <-- this should be 319233
... and on and on
This took me a while to figure out, but it came down to altering number to number + i in this code:
if (i == breakoutArray[index]) {
index += 1;
number = number + i;
recursivePrint(index, breakoutArray, number);
}
Using number = number + i sets number in that stack frame, as well as all subsequent recursive stack frames. This was remedied by passing number + i in the recursive call, via recursivePrint(index + 1, breakoutArray, number + i).
The complete, working, method code follows:
public void recursivePrint(int index, int[] breakoutArray, String number) {
//number=319 is a String
for (int i = 0; i <= 9; i++) {
if ((index < breakoutArray.length - 1) && i == breakoutArray[index]) {
recursivePrint(index + 1, breakoutArray, number + i);
} else {
if((index == breakoutArray.length - 1) && i == breakoutArray[index]) {
rightOutputBText.append(number + i + " bingo\n");
} else {
rightOutputBText.append(number + i + "\n");
}
}
}
} //end of recursivePrint method
Output using 319 and 3192310 follows:
3190
3191
31920
31921
31922
319230
3192310 bingo
3192311
3192312
3192313
3192314
3192315
3192316
3192317
3192318
3192319
319232
319233
319234
319235
319236
319237
319238
319239
31924
31925
31926
31927
31928
31929
3193
3194
3195
3196
3197
3198
3199

Issues with loops? Program runs as it should but test keep failing. Java using TMCbeans

I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.

What is causing my dice game to show an unrealistic amount of perfect rolls

I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.

java - Read & determine number of integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a new bee in java ... so I have an assignment and I am stuck can somebody help me
I have to write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zero's). The program should end when the user inputs 0.
Sample run:
Enter an int value (the program exits if the input is 0: 1 3 -1 2 0
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
The thing which i wrote is ... The logic seems right but it does not work ...
The code that I wrote is
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
while (data !=0)
{
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data < 0 || data > 0){
count++;
if (data >0)
positive++;
else if (0<data)
negative++;
count = count + data;
count++;
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of average is " + count/data ;
JOptionPane.showMessageDialog(null, strOutput);
}
}
In your while loop condition, you're checking if data !=0 which returns false and the while loop code block doesn't execute, because the data is set to int data = 0; at the beginning of program.
There are 2 simple solutions to your problem:
Set data to something other than 0
Use do...while loop, see example below
int data = 0;
...
do{
...
} while (data != 0);
Two errors here:
Your loop will never execute, since on the initial run, data == 0. You can fix this by asking the question early as opposed to later:
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
int data = Integer.parseInt(strdata);
Then, later in the loop (towards the bottom):
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
Even if you were able to enter the loop, you'd get all positive number counts and no negative number counts. The reason for this: data > 0 and 0 < data are equivalent boolean statements.
What you probably meant was this:
if (data > 0) {
positive++;
} else if (data < 0) {
negative++;
}
As others have said, initializing data to is a problem, but see below for my advice there.
The other issue you're going to run into is you're having count do too much.
Assume count starts at 0 and the user enters 3.
In
if (data < 0 || data > 0){
count++;
You're now at one, the you go into
count = count + data;
count++;
And count goes up to 4, then ++ up to 5.
Even if you've got a 0 entered, you still alter count before breaking the loop.
Try something like Orel mentioned with having a sum int that just keeps track of the sum. Keep count only to count, and only the count++ at the very bottom, completely erase
if (data < 0 || data > 0){
count++;
Instead, try something like this for the 0 check to prevent screwing with the whole thing:
while(true){
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
if (data == 0)
break;
...
}
You could use a do/while here as well. This will allow you to initialize data to whatever (or nothing) that you like. Another thing, make sure that they value they enter is not null and is an int, your professor will definitely enter "sleirjwlfie" when prompted for a number because it's best practice to assume the user will break your program. So something in pseudo-code like:
while(true){
// get value from user
// if value is null OR value is not an int
continue;
}
I'll let you sort out the how to there as to not kill the learning experience, but I know that kind of thing bit me in school more than once.
Good luck!
+1 for attempting and writing almost working code :)
As others have pointed out your code has few bugs which needs to be fixed.
Your assignment to data should happen at least once before entering
while(data) loop.
You don't need to check value of input before incrementing count, if
it's 0 then you won't enter loop. Otherwise you will have to
increment count anyways.
For calculating total and average you need to use one more variable
Are you using any IDE ?
Use IDE (Eclipse is one of the best one) and debug your code step by step to check what's happening.
Google for how to use IDE and debug.
Below is working code for your reference.
import javax.swing.*;
public class AverageNumbers {
public static void main(String[] args)
{
int data = 0;
int positive = 0;
int negative = 0;
int count = 0;
int total = 0;
double avg = 0;
String strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
while (data !=0)
{
if (data >0) {
positive++;
} else {
negative++;
}
total = total + data;
count++;
strdata = JOptionPane.showInputDialog ("Enter the integer The input ends if the value is 0") ;
data = Integer.parseInt(strdata);
}
String strOutput = "The number of positives is " + positive;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of negatives is " + negative;
JOptionPane.showMessageDialog(null, strOutput);
strOutput = "The number of total is " + count ;
JOptionPane.showMessageDialog(null, strOutput);
avg = total * 1.0 /count ;
strOutput = "The number of average is " + avg;
JOptionPane.showMessageDialog(null, strOutput);
System.exit(0);
}
}
Well, the first problem is here. You initialize data to 0:
int data = 0;
Then your loop condition checks for data != 0 :
while (data !=0) {
...
}
Since data is assigned 0, the loop is never entered.
You should add a 'sum' int variable and change this line
count = count + data;
With this
sum += data;
Also change your while-loop to do-while loop.

java using for loops [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Please help me in using for loops, for I am fairly new to Java. When I ran my program, the compiler threw out an error saying that my for loop is not a statement and it hinted at the variable guess, so I put String in front of guess because I declared it as a String. After I compiled this newly edited program, it threw out another error, this time saying that the variable guess was already declared outside of the for loop. Is there any way that I can use a variable declared outside of the for loop in the for loop? Here is the code:
import java.util.Scanner;
import java.util.Random;
public class Lottery{
public static void main(String args[]){
// create Scanner object
Scanner in;
in = new Scanner(System.in);
// create counter variable
int counter = 0;
// prompt user to choose between and including 000 and 999
System.out.print("Please pick a number between and including 000 and 999: ");
// initialize guess
String guess = in.next();
// get first two digits of guess
String firstTwoDigitsGuess = guess.substring(0, 2);
// get last two digits of guess
String lastTwoDigitsGuess = guess.substring(1);
// create Random number
Random number = new Random();
// initialize range
int range = number.nextInt(1000);
// convert int range to String
String rangeString = Integer.toString(range);
// firstTwoDigits declaration and initialization for first two digits of rangeString
String firstTwoDigitsString = rangeString.substring(0, 2);
// secondTwoDigits declaration and initialization for last two digits of rangeString
String lastTwoDigitsString = rangeString.substring(1);
// firstTwoDitigsRangeTrailingZero declaration and initialization
String firstTwoDigitsRangeTrailingZero = "";
// secondTwoDigitRangeTrailingZero declaration and initialization
String lastTwoDigitRangeTrailingZero = "";
// while statement
for(guess; !guess.equals(rangeString); ){
// if-else-if statement for trailing zeroes
if(range < 100){
// create zero variable
char zero;
zero = '0';
// create number with one trailing zero
int oneTrailingZero;
oneTrailingZero = zero + range;
// convert int oneTrailingZero to String
String oneTrailingZeroString = Integer.toString(oneTrailingZero);
// create first two digits of one trailing zero
String firstOneTrailingZeroString = oneTrailingZeroString.substring(0, 1);
// create last two digits of one trailing zero
String lastOneTrailingZeroString = oneTrailingZeroString.substring(1);
// // nested if-else-if statements
// all digits match
if(guess.equals(oneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Perfect guess, all digits match!");
// first two digits match
}else if(firstTwoDigitsGuess.equals( firstOneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("The first two digits match!");
// last two digits match
}else if(lastTwoDigitsGuess.equals( lastOneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("The last two digits match!");
}else{
// do nothing
}
}else if(range < 10){
// create doubleZero variable
String doubleZero = "00";
// create number with double trailing zeroes
String doubleTrailingZero;
doubleTrailingZero = doubleZero + range;
// create first two digits of double trailing zeroes
String firstDoubleTrailingZeroString = doubleTrailingZero.substring(0, 1);
// create last two digits of double trailing zeroes
String lastDoubleTrailingZeroString = doubleTrailingZero.substring(1);
// // nested if-else-if statements
// all digits match
if(guess.equals(doubleTrailingZero)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Perfect guess, all digits match!");
// first two digits match
}else if(firstTwoDigitsGuess.equals( firstDoubleTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Firt two digits match!");
// last two digits match
}else if(lastTwoDigitsGuess.equals( lastDoubleTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Last two digits match!");
}else{
// do nothing
}
// wrong guess
}else{
// notify user's guess is wrong
System.out.println("The guess you chose was wrong. You did not get a perfect guess. Neither did your first or last two digits match the random number. The random number was: " + range);
}
}
}
}
You don't need the guess in the for loop as it is not instantiating it. Instead try...
for( ; !guess.equals(rangeString); ) {...}
I'm pretty sure that's why it's hinting at it. Typically, at least in Java, if no variable is being created in the for, then it complains if you do as you did. For instance, this...
int i = 0;
for(i; i < 10; ++i) {...}
complains while this...
for(int i = 0; i < 10; ++i) {...}
does not.
a for loop works very similar to a while loop for example,
int i = 0;
while(i < 4){
//do stuff
i++;
}
is the same as
for(int i = 0; i < 4; i++){
//do stuff
}
So in the first part, you are defining a variable, in the second part, you are saying "keep going as long as this is true" and in the end you are saying "do this at the end of each loop"
So try
for( ;!guess.equals(rangeString); ){//your code}
However you would probably be better off replacing your for loop with this:
while(!guess.equals(rangeString)){//your code}
Loop statements are formed like this:
for(int i = 0; i < 10; i++){
// start^ end^ ^increment
}

Categories