Let's say I have five int variables that are prompted for user input. User keys in the five value and two of those values are 0. I would like to ONLY print out values that are greater than zero.
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
I would like to write a dynamic print statement that would exclude the int variables with Zero value.
Currently, my print statement displays all values:
System.out.printf("%s %d%n%s %d%n%s %d%n%s %d%n%s %d%n","V1;","v1","V2:","v2","V3:","v3","V4:","v4","V5:","v5");
I tried writing if-else statements but that became very cumbersome.
Create a new method printNonZeroVars(Integer... ints).
public static void main(String[] args) {
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
printNonZeroVars(v1, v2, v3, v4, v5)
}
public void printNonZeroVars(int... ints) {
for (int i = 0; i < ints.length; i++) {
if (ints[i] > 0) {
System.out.printf("V%d%d%n", i, ints[i]);
}
}
}
I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.
So a simple way of achieving this would be to use some sort of Array/List.
ArrayList<Integer> list = new ArrayList<Integer>()
// Or as pointed out by David a better way would be to declare the list as
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
....
Once you have the list you can use a loop to loop through the list and do relevant checks - something like this
String str = "";
for(int i=0; i<list.size(); i++) {
if(list.get(i) == 0) {
continue;
}
str += "v"+i + ":" + Integer.toString(list.get(i));
}
System.out.println(str);
Its pseudo but should give you a good head start :)
Related
I'm new at programming. I have to write a code, main requirements - user chooses the sorting method (one is already added, the second one I will add later), enters the amount of elements in the array, enters the elements and then the code sorts them. But it looks like the code only takes the last entered element and tries to sort it. What do I have to do to make it sort all entered elements?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("181RDB094 Līva Gundega Ermansone 1");
System.out.print("method:");
int M;
if (sc.hasNextInt())
M = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
System.out.print("count:");
int count = sc.nextInt();
int[] masīvs = new int[count];
System.out.println("items:");
masīvs = new int[count];
for (int i = 0; i < count; i++) {
masīvs[i] = sc.nextInt();
}
System.out.println("result:");
if (M == 1) {
int[] b = new int[count];
int[] less = new int[count];
int[] equal = new int[count];
int k;
for (int i = 0; i < count; i++)
for (int j = 0; j < count; j++) {
if (masīvs[i] == masīvs[j]) {
equal[i] = i++;
} else if (masīvs[i] > masīvs[j]) {
less[i] = i++;
}
}
for (int i = 0; i < count; i++) {
k = less[i];
for (int j = 0; j < equal[i]; j++) {
b[k + j] = masīvs[i];
}
}
for (int i = 0; i < count; i++) {
masīvs[i] = b[i];
System.out.print(masīvs[i] + " ");
}
} else if (M == 2) {
} else {
System.out.println("input-output error");
return;
}
}
Sorry for the ugly code, it's just a draft.
Expected:
181RDB094 Līva Gundega Ermansone 1
method:1
count:4
items:
13
31
55
2
result:
55 31 13 2
Actual results:
181RDB094 Līva Gundega Ermansone 1
method:1
count:4
items:
13
31
55
2
result:
2 2 2 0
You can add a simple for loop after filling your array to check the contents. There, you can see that all entries are written into the array correctly.
This will output:
Array:13
Array:31
Array:55
Array:2
for (int i = 0; i < masīvs.length; i++) {
System.out.println("Array:" + masīvs[i]);
}
The sorting method you are following fixes a set of equal elements at their proper position by finding the no of elements less than those elements.
The problem in sorting lies in finding the no of elements less and equal to.
equal[i]++; instead of equal[i]=i++;
Similarly,
less[i]++; instead of less[i]=i++;
If you're using Java 8 or more recent, you may be able to use the ArrayList class (with the Integer class) instead of an 1D array (i.e. int[] var = new int[x]); it would allow you to use its sort(Comparator) method instead.
You would have to create a Comparator instance (lambda function, or anonymous) or an implementing class, unless you want to use the natural ordering of those.
It would give you something around those two lines:
ArrayList<Integer> var = new ArrayList<>();
and var.sort(); (assuming you use the natural ordering)
It might however be harder to manipulate at first, if you're new to the Java Collection Framework, so don't hesitate to ask questions.
P.S.: I might have misunderstood the code, so just tell me so I can fix my answer.
P.S.S.: Somewhat unrelated, and it's probably in your mind (ignore that part then), but I would recommend you to refactor that into much more smaller methods/functions.
I think that your code organization is very bad. It's easier to give you more correct solution, than count and fix your problem:
public class Foo {
public static void main(String... args) {
final BiFunction<int[], Comparator<Integer>, int[]> sort =
(items, comparator) -> Arrays.stream(items)
.boxed()
.sorted(comparator)
.mapToInt(i -> i)
.toArray();
try (Scanner scan = new Scanner(System.in)) {
Comparator<Integer> comparator = getSortingMethod(scan);
int[] items = getItems(scan);
int[] sorted = sort.apply(items, comparator);
System.out.println(Arrays.toString(sorted));
}
}
private static final Comparator<Integer> SORT_ASC = Comparator.naturalOrder();
private static final Comparator<Integer> SORT_DESC = Comparator.reverseOrder();
private static final Comparator<Integer> SORT_NULL = (one, two) -> {
throw new IllegalArgumentException("input-output error");
};
private static Comparator<Integer> getSortingMethod(Scanner scan) {
System.out.println("181RDB094 Līva Gundega Ermansone 1");
System.out.print("method:");
try {
int M = scan.nextInt();
if (M == 1)
return SORT_DESC;
if (M == 2)
return SORT_ASC;
return SORT_NULL;
} catch(RuntimeException e) {
return SORT_NULL;
}
}
private static int[] getItems(Scanner scan) {
System.out.print("count:");
int[] items = new int[scan.nextInt()];
System.out.println("items:");
for (int i = 0; i < items.length; i++)
items[i] = scan.nextInt();
return items;
}
}
okay so we basically have this question to answer, but I am very confused and don't know how to use recursion to get all possible combinations.. Please someone save me!
Write a public static method threadings, which takes an int n (representing the number of beads on each necklace) and a Set of Strings (representing the available bead colours; your code must not alter this Set),and returns a Set of ArrayLists of Strings, representing all the orders in which n beads of the given colours can be threaded. If n < 1, return a Set containing just one, empty, ArrayList.
Examples of correct behaviour:
• threadings(0, {red,green}) = {[]}
• threadings(1, {red,green}) = {[red],[green]}
• threadings(2, {red,green})
= {[red,red],[red,green],[green,red],[green,green]}
• threadings(3, {red}) = {[red,red,red]}
Hint: you will probably want threadings to call itself recursively, although
full marks are available for any correct method.
This is what I have written until now:
public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){
HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>();
ArrayList<String> inresult= new ArrayList<String>();
String[] col= new String[colours.size()];
if (n==0){
result.add(inresult);
return result;
}else{
}
}
Try this:
public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) {
List<String> colorsList = new ArrayList<>(colours);
ArrayList<String> resultList = new ArrayList<>();
HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>();
int carry;
int[] indices = new int[n];
do
{
for(int index : indices) {
resultList.add(colorsList.get(index));
}
result.add(resultList);
resultList = new ArrayList<>();
carry = 1;
for(int i = indices.length - 1; i >= 0; i--)
{
if(carry == 0)
break;
indices[i] += carry;
carry = 0;
if(indices[i] == colorsList.size())
{
carry = 1;
indices[i] = 0;
}
}
}
while(carry != 1);
return result;
}
I have to create a program which adds two integers and prints the sum vertically.
For example, I have.
a=323, b=322.
The output should be:
6
4
5
I've created the code for when the integers are up to two digits, but I want it to work for at least three digits.
Below is the best I could think of.
It may be completely wrong, but the only problem I'm facing is the declaration of array.
It says that the array might not be initialized.
If I set it to null then also it won't assign values to it later.
I know maybe I'm making a big mistake here, but I'll really appreciate if anyone could help me out.
Please keep in mind that I must not use any other functions for this code.
Hope I'm clear.
public class Vert
{
public static void main(String args[])
{
int n,i=0,j,a=323,b=322;
int s[];
n=a+b;
while(n>9)
{
s[i]=n%10;
i++;
s[i]=n/10;
if(s[i]>9)
{
n=s[i];
}
}
j=i;
for(j=i;j>=0;j--)
{
System.out.println(+s[j]);
}
}
}
String conversion seems like cheating, so here's a Stack.
int a = 323, b = 322;
java.util.Stack<Integer> stack = new java.util.Stack<>();
int n = a + b;
while (n > 0) {
stack.push(n % 10);
n = n / 10;
}
while (!stack.isEmpty())
System.out.println(stack.pop());
If an array is required, you need two passes over the sum
int a = 323, b = 322;
// Get the size of the array
int n = a + b;
int size = 0;
while (n > 0) {
size++;
n = n / 10;
}
// Build the output
int s[] = new int[size];
n = a + b;
for (int i = size - 1; n > 0; i--) {
s[i] = n % 10;
n = n / 10;
}
// Print
for (int x : s) {
System.out.println(x);
}
To initialize an array, you need to specify the size of your array as next:
int s[] = new int[mySize];
If you don't know the size of your array, you should consider using a List of Integer instead as next:
List<Integer> s = new ArrayList<Integer>();
Here is how it could be done:
// Convert the sum into a String
String result = String.valueOf(a + b);
for (int i=0; i <result.length();i++) {
// Print one character corresponding to a digit here per line
System.out.println(result.charAt(i));
}
I'd do it like this:
int a = 322;
int b = 322;
int sum = a + b;
String s = Integer.toString(sum);
for(int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
But your problem looks like an array is required.
The steps are same as in my solution:
Use int values
Sum the int values (operation)
Convert the int value in an array/string
Output the array/string
So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.
I have written some code for sorting random integers that a user inputted. How would I switch this into sorting randomly inputted letters? Aka, user inputs j, s, g, w, and the programs outputs g, j, s, w?
for (int i = 0; i < random.length; i++) { //"random" is array with stored integers
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j] < random[x]) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final int temp = random[i];
random[i] = random[x];
random[x] = temp;
}
itsATextArea.append(random[i] + "\n");// Output ascending order
}
Originally I hoped (though I knew the chances of me being right were against me) that replacing all the 'int' with 'String' would work...naturally I was wrong and realized perhaps I had to list out what letter came before which by using lists such as list.add("a"); etc.
I apologize if this seems like I am asking you guys to do all the work (which I'm not) but I'm not entirely sure how to start going about this, so if anyone can give some hints or tips, that would be most appreciated!
You could use String.compareTo() to do that:
Change this:
int[] random = new int[sizeyouhad];
...
if (random[j] < random[x]) {
...
final int temp = random[i];
to:
String[] random = new String[sizeyouhad];
...
if (random[j].compareTo(random[x]) < 0) {
...
final String temp = random[i];
Trial with your code:
String[] random = new String[3];
random[0] = "b";
random[1] = "c";
random[2] = "a";
int x = 0;
//"random" is array with stored integers
for (int i = 0; i < random.length; i++) {
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j].compareTo(random[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = random[i];
random[i] = random[x];
random[x] = temp;
}
System.out.println(random[i] + "\n");// Output ascending order
}
If you're just trying to sort a list of strings you should probably use the java.util.Collections.sort method rather than writing your own sorting routine.
Was random originally int[]? If you had changed this to String[], you can use String#compareTo method to discern if one string is "less than" another.
Incidentally, you can change the type of random to Comparable[] and then you can use the same algorithm to sort any object whose class implements the interface!
Try to use Collections.sort() function
List<String> l = Arrays.asList("j","s", "g","w");
Collections.sort(l);
If you consider every character to be a code point[1] and you want to sort by Unicode code point order[2], then there is really no need to change your logic. The work is converting from whatever input you are given (String, char[], etc.) into an int[] of the code points.
[1] - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#codePointAt(int)
[2] - http://en.wikipedia.org/wiki/Code_point
You can make your code work on any type of Object by using generics.
The following code is very simple and works perfectly (With this library you can solve your problem in few lines):
import static ch.lambdaj.Lambda.sort;
import static ch.lambdaj.Lambda.on;
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
List<String> list = Arrays.asList("1","102","-50","54","ABS");
List<String> newList = sort(list, on(String.class));
System.out.println(newList);//[-50, 1, 102, 54, ABS]
}
}
This code uses lambda library (download here, website). Find in the website this example:
List<Person> sorted = sort(persons, on(Person.class).getAge());