How to expand a number to match another in Java - 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

Related

Split string in Java at certain characters, return the amount of times a message needs to be split

I haven't coded in Java for a long time and during the lockdown working on getting back into it. I have this puzzle I've come across and wondering if someone can help me with it:
1). Split the given string into the size of the given int
2). return how many times the string would need to be split for the given int
3). no splitting words
String random = "I want to take this and only send it at a certain number";
int random_number =12;
public int splitTheString (String random, int random_number) {
int total = 0;
int counter = 0;
String [] str = random.split(" ");
for(int i=0; i<str.length;i++)
{
total += str[i].length();
if(total < random_number){
System.out.println(str[i] + " less than 12");
counter ++;
} else {
System.out.println(str[i] + " More than 12");
counter ++;
}
System.out.println(total + " " + counter);
return counter;
}
}
So from main the method would be called: splitTheString (random, random_number)
I'm trying something like the above but think Im headed in the wrong direction. Can someone help out. Thanks
Edit:
Expected input:
Strings:
1). "Messages won't be too long"
2). "These messages are great"
3). "Random messages are fun to play with"
4). "Some won't be words like kkkk lllll pppp llll"
5). "All these will be the kinds of inputs"
Expected outputs, can be split:
1). "Messages", "won't be too", "long" => 3
2). "These", "messages are", "great" => 3
3). "Random", "messages are", "fun to play", "with" => 4
4). "Some won't be", "words like", "kkkk lllll", "pppp llll" => 4
5). "All these will", "be the kinds of", "inputs" =>
First of all, DEBUG your code, follow the changes of the variables value on every iteration, I am sure you can see where the things start going wrong.
Beloved is just an example, start with
static int splitter(String fullSentence, int maxChar) {
do string-split as you did, define two variables, one for count like yours, other for the current split word(s),
String split = "";
int count = 0;
iterate the words of full sentence,
for (int i = 0; i < words.length; i++) {
check if split + words[i] 's length is less than the maxChar, do not forget to add 1 for blank between the words,
// check if words[i] is blank or empty!!!
if (split.concat(words[i]).length() + 1 <= maxChar) {
split = split.length() == 0 ? words[i] : split.concat(" " + words[i]);
}
else {
// we reached max possible chars
if (split.length() > 0) {
System.out.print(split + ", ");
count++;
}
split = words[i];
}
when you finished the iteration, check again if split words has some value, even check if it includes last word of full sentence then report it and increase the count if necessary
System.out.println(" => " + count);
end return the count;
return count;

How to return the correct value from an int[] array?

I'm new to Java (and programming in general), so apologies if some of this doesn't make sense and/or if the code is really bad:
I am trying get a unique four digit code from a user input (that is what the Keyboard.readInput line does), and I have put in a couple of conditional statements to ensure that the code that is entered can only be 4 digits and that each digit must be different to the other three.
The if statements work as intended in the sense that they output the error message and prompt them to re-enter (i.e. the method getPlayerGuess() gets called). For example, if the user enters 123 (i.e. userGuess.length() != 4), it will prompt them to enter again. If they then enter 1234, the method will complete.
However, the problem I have is that when I call this method in another class that I have, the code that is being pulled through is the first code entered (i.e. 123) and not the four digit one I want (i.e. 1234) - which is resulting in an array IndexOutOfBoundsException.
Any ideas on how I can ensure that the code that is being returned is the four digit one that passes the conditionals, and not the first one entered?
public int[] getPlayerGuess() {
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
getPlayerGuess();
}
int[] userCode = createArrayFromGuess(userGuess);
for (int i = 0; i < userCode.length-1; i++){
for (int j = i+1; j < userCode.length; j++){
if (userCode[i] == userCode[j]) {
System.out.print("Code must have four unique digits - ");
getPlayerGuess();
}
}
}
return userCode;
}
You call getPlayerGuess() which returns an int[] but you do not collect, nor assign the return value. Nor do you return it... so something like the following may work for you:
public int[] getPlayerGuess() {
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
return getPlayerGuess(); // either assign or return the value that is actually calculated within that call...
}
int[] userCode = createArrayFromGuess(userGuess);
for (int i = 0; i < userCode.length-1; i++){
for (int j = i+1; j < userCode.length; j++){
if (userCode[i] == userCode[j]) {
System.out.print("Code must have four unique digits - ");
return getPlayerGuess(); // either assign or return the value that is actually calculated within that call...
}
}
}
return userCode;
}
Simplifying your code a bit (not too much ;-)):
public int[] getPlayerGuess(String msg) {
System.out.print(msg);
String userGuess = Keyboard.readLine();
if (userGuess.length() != 4) {
return getPlayerGuess("\nYour code must be 4 digits - ");
}
if (userGuess.chars().distinct().count() != 4) {
return getPlayerGuess("\nCode must have four unique digits - ");
}
return createArrayFromGuess(userGuess);
}
with the initial call being:
getPlayerGuess("Guess a four digit code: ");
Note that you can write this code also using an iterative approach. But I will leave that up to you.
Your problem lies here:
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
getPlayerGuess();
}
Yes, you call the method a second time, but you completely ignore that, and don't do anything with the result of it.
Change it to this:
if (userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
return getPlayerGuess();
}
So you'll return the result of the new call, instead of completing the code after the if block.
EDIT:
A better approach would be:
System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();
while(userGuess.length() != 4) {
System.out.print("Your code must be 4 digits - ");
System.out.print("Guess a four digit code: ");
userGuess = Keyboard.readInput();
}

Java: Adding and Subtracting Digits Taken from a String

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.

How to number each line in the output using a for loop?

import java.util.Scanner;
public class LoveCS
{
public static void main(String[] args)
{
int noTimesPrinted;
Scanner scan = new Scanner(System.in);
System.out.print("How many times should the message be printed: ");
noTimesPrinted = scan.nextInt();
int count = 1;
while (count <= noTimesPrinted)
{
System.out.println(" I love Computer Science!!");
count++;
}
}
}
Instead of using constant LIMIT, ask the user how many times the message should be printed. You will need to declare a variable to store the user’s response and use that variable to control the loop. (Remember that all caps is used only for constants!)
I HAVE COMPLETED PART1. I AM STUCK ON PART2. How do I get the number sequence??
Number each line in the output, and add a message at the end of the loop that says how many times the message was printed. So if the user enters 3, your program should print this:
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times.
If the message is printed N times, compute and print the sum of the numbers from 1 to N.
So for the example above, the last line would now read:
Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
Note that you will need to add a variable to hold the sum.
You have a few choices. You could use String concatenation,
int count = 1;
while (count <= noTimesPrinted)
{
System.out.println(Integer.toString(count) + " I love Computer Science!!");
count++;
}
System.out.println("Printed this message " + noTimesPrinted + " times");
Or with printf and (since you said you wanted a for loop) something like
for (int count = 1; count <= noTimesPrinted; count++) {
System.out.printf("%d I love Computer Science!!%n", count);
}
System.out.printf("Printed this message %d times%n", noTimesPrinted);

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.

Categories