Adding one to the set of numbers in the array Java - java

public class Test
{
public static int addOne(int[] numb)
{
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]+1);
int result = numb[i];
}
return (numbers.length);
}
}
Main:
public class Main
{
public static void main(String[] args)
{
int[] numO = {2,2,4,4,6};
System.out.println(Test.addOne(numO)); /
}
}
Output:
3,3,5,5,7,5
I was trying out arrays in java as I am starting to learn arrays, I set five numbers in the array and using a for loop, wanted to add the numbers in the array by 1, e.g. Array containing (1,2,3) would be (2,3,4) and outputting the total number 9, instead of 2,3,4 and a random number. How can I achieve this?

You are never actually changing the value contained within the numb array, what you are doing is taking the existing value and adding outputting it with 1 added to it
System.out.println(numb[i] + 1);
To change the value you must increment the value outside
numb[i]++;
System.out.println(numb[i]);
That should solve your problem of not retaining the changed value in the array. However there is another error that I can see that would prevent you from outputting the correct result value. By doing result + numb[i]; you are preforming an operation but not setting the result variable equal to anything. To set it add to the value it already contains you would do result = result + numb[i] or more properly result += numb[i]
Hope this helps!

Related

java - make variable persistent on multiple method calls

I want the variable called "number" to stay the same value when the method is called multiple times. It seems like it resets between each method call. I don't see why it would because the variable is declared outside the method.
This is the first class:
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
for(int counter = 0; counter < 5; counter++) {
Output display = new Output();
display.outputNumber();
}
}
}
This is the second class:
public class Output {
int number;
public void outputNumber() {
number++;
System.out.println(number);
}
}
When I run this, it outputs
1
1
1
1
1
I want it to output:
1
2
3
4
5
Moving this line of code: Output display = new Output(); outside the loop should give you the desired output.
Each time you create a new object, the number of that object is initialized to 0, which explains your current output.
Reusing the object reuses number, and hence you get the desired output.
Every time you create a new Output(), you create a new object that starts from scratch. In this case, you are creating 5 new objects, incrementing each only once, and getting your series of 1s.
You will probably want to create a single Output outside of the loop and then simply increment inside the loop. That way it's the same object, and the values are thus maintained.
Your Output object is getting created for each loop and the number variable of the Output class is always instantiated to the default int value of 0. Hence each time it increments 0 to 1 and displays only 1.
You could either drop incrementing the number variable in the Output class and do the increment in the actual class and pass the value to the Output class.
public class Output {
int number;
public Output (int number) {
this.number = number;
}
public void outputNumber() {
System.out.println(number);
}
}
And accordingly, change your calls to the Output class from the for loop in the Input class as well.
You also might want to change the for loop counter variable instantion from 0 to 1 and change the condition check to <=5 instead of <5.

10 ×10 multiplication table, but only shows those entries which are greater than a value entered by the user

I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,

Java Error - .charAt() returning two characters in a string of numbers

I am selecting certain digits out of a large number. I'm saving the number in a string, and then saving each character as a subarray. This is what I have so far (I'm not finished). But when this code runs, System.out.print(v[0]) returns "55". I can't understand why. Printing anything else returns a similiarly (seemingly) random two numbers.
Thanks!
public class P432 { public static void main(String[] args) {
String x = "73167176531330624919225119674426574742355349194934"+
"96983520312774506326239578318016984801869478851843"+
"85861560789112949495459501737958331952853208805511"+
"12540698747158523863050715693290963295227443043557"+
"66896648950445244523161731856403098711121722383113"+
"62229893423380308135336276614282806444486645238749"+
"30358907296290491560440772390713810515859307960866"+
"70172427121883998797908792274921901699720888093776"+
"65727333001053367881220235421809751254540594752243"+
"52584907711670556013604839586446706324415722155397"+
"53697817977846174064955149290862569321978468622482"+
"83972241375657056057490261407972968652414535100474"+
"82166370484403199890008895243450658541227588666881"+
"16427171479924442928230863465674813919123162824586"+
"17866458359124566529476545682848912883142607690042"+
"24219022671055626321111109370544217506941658960408"+
"07198403850962455444362981230987879927244284909188"+
"84580156166097919133875499200524063689912560717606"+
"05886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";
int[] v = new int[1000];
for (int g=0; g<1000; g++)
{
v[g] = x.charAt(g);
}
System.out.print(v[0]);
}}
As Jim said, you need to change the array to be char instead of int.
By the way, you can use v.length instead of the number 1000 in the for loop.
.length returns the length (size) of the array (1000 in this case), so if you'll want to change the array size in the future - you won't need to change the for loop condition.

Java - Trouble reading data from a list of 2D arrays

I have created a list of 2D arrays containing randomly generated number values for different locations.
public static int Prices[][] = new int[Cities.length][ItemNames.length];
public static List<int[][]> CityPrices = new ArrayList<int[][]>();
public static void NewDay()
{
for(int i = 0; i<Cities.length; ++i)
{
Prices[i] = PriceGenerator.ReturnPricesForCity(i);
//This method returns an array of random integers
}
CityPrices.add(Prices);
}
But then later when I want to retrieve the price history for a specific item for the amount of days passed, it returns the same value for each day
int Prices[] = new int[GlobalVariables.CityPrices.size()];
String sTest = "";
for(int i = 0; i < Prices.length; ++i)
{
Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()];
sTest = sTest + Prices[i] + ",";
}
In this case, the values returned by sTest was : 6055,6055,6055,6055,6055, for five consecutive days.
If I would for instance add a day, the values would change to a range of a new number, which in this case was : 7294,7294,7294,7294,7294,7294,
Please show me what I am doing wrong, as I have been trying to figure this one out the past 4 days with no luck.
Every element in your CityPrices list is the same: in each case, you are adding the Prices two-dimensional array. Your loop modifies Prices[i], but it doesn't change Prices, which is still a reference to the same two-dimensional array right the way through.
I think you're imagining it will pass the contents of the array in its current state, but it doesn't: it passes a reference to the array to the .add() method, so any subsequent changes to the array will be reflected in the contents of CityPrices.
If at the end of your loop you try
CityPrices.get(0) == CityPrices.get(1)
you'll see it returns true.
In the assignment: Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()]; you are basically referencing an int[][] at the same index for both dimensions.
On top of that, the spinCity.getSelectedItemPosition() invocation might be returning the same index at every iteration of your loop, hence your identical values.
It's hard to assume anything further as you haven't posted the code for spinCity.

recursion using a hashmap

I have an array that has the following numbers
int[] arr = {2,4,3,1,5,6,0,7,8,9,10,11,12,13,14,15};
Or any other order for that matter.
I need to make all the possible combinations for the numbers using a recursion but satisfying a condition that the next number clubbed with the present one can only be from specific numbers given by a hashmap:
ex When the recursion takes 1 the next number can be from {0,4,5,2,6} (from the HaspMap),and then if i make 10,the next number can be from {1,4,5} and so on
static HashMap<Integer,Integer[]> possibleSeq = new HashMap<Integer,Integer[] >();
private static void initialize(HashMap<Integer,Integer[]> possibleSeq) {
possibleSeq.put(0,new Integer[]{1,4,5});
possibleSeq.put(1,new Integer[]{0,4,5,2,6});
possibleSeq.put(2,new Integer[]{1,3,5,6,7});
possibleSeq.put(3,new Integer[]{2,6,7});
possibleSeq.put(4,new Integer[]{0,1,5,8,9});
possibleSeq.put(5,new Integer[]{0,1,2,4,6,8,9,10});
possibleSeq.put(6,new Integer[]{1,2,3,5,7,9,10,11});
possibleSeq.put(7,new Integer[]{2,3,6,10,11});
possibleSeq.put(8,new Integer[]{9,4,5,12,13});
possibleSeq.put(9,new Integer[]{10,4,5,8,6,12,13,14});
possibleSeq.put(10,new Integer[]{7,6,5,9,11,15,13,14});
possibleSeq.put(11,new Integer[]{6,7,10,14,15});
possibleSeq.put(12,new Integer[]{8,9,13});
possibleSeq.put(13,new Integer[]{8,9,10,12,14});
possibleSeq.put(14,new Integer[]{9,10,11,13,15});
possibleSeq.put(15,new Integer[]{10,11,14});
}
Note: I am required to make all the possible numbers beginning from digit length 1 to 10.
Help!
Try with something like this, for starters:
void findPath(Set paths, Stack path, int[] nextSteps, Set numbersLeft) {
if (numbersLeft.isEmpty()) {
//Done
paths.add(new ArrayList(path));
return;
}
for (int step:nextSteps) {
if (numbersLeft.contains(step)) {
// We can move on
path.push(step);
numbersLeft.remove(step);
findPath(paths, path, possiblePaths.get(step), numbersLeft);
numbersLeft.add(path.pop());
}
}
}
Starting values should be an empty Set, and empty Stack, a nextSteps identical to you initial array, and a set created from your initial array. When this returns, the paths Set should be filled with the possible paths.
I haven't tested this, and there are bugs as well as more elegant solutions.

Categories