Printing out multiple values assigned to a single variable - java

I have a for loop that will continue until i is not less than the maxnum as shown in the code. In the meantime it will do modulo operation and I am trying to accumulate as much values as possible to the variable that I can assign with. My problem is in the code is that it only does the single operation and will not continue to do the operation and have multiple values assign to it. Should I change my loop.
tried assigning an array list
having i++ below
for(int i =1; i < maxnum; i++ ) {
MulT = i % divisor;
}
if ( MulT==0 ) {
System.out.println("Multiples of " + dividend+ " between 1 and "+ maxnum +" is");
System.out.println(MulT);
}
else {
System.out.println("Multiples of " + dividend + " between 1 and " + maxnum+ "are:");
System.out.print("No numbers were found");
}
Multiples of 2 between 1 and 10 are:
2
4
6
8
10

If you want to get all the values stored in variables then you have to iterate that variable in for loop after that print that variable in console, check the below code.
int maxnum=10;
int divisor=2;
int val[] = new int[maxnum];
int j=0;
for(int i =1; i <= maxnum; i++ ) {
double MulT = i % divisor;
if(MulT==0){
val[j]=i;
j++;
}
}
if(val[0] > 0){
System.out.print("Multiples of " + divisor+ " between 1 and "+ maxnum +" is:");
for(int k=0;k < val.length;k++){
if(val[k]!=0){
System.out.print(" "+val[k]);
}
}
}else{
System.out.println("Multiples of " + divisor + " between 1 and " + maxnum+" are:");
System.out.print("No numbers were found");
}

Related

JOptionPane Looping

I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);

Output line repeats using while loop?

I am just beginning to learn Java and still getting used to while loops. I would like the output statement to only show once instead of multiple times. For example, the statement should say:
"Even integers between 1 and 5 are: 2 4"
instead of:
"Even integers between 1 and 5 are:
2
Even integers between 1 and 5 are:
Even integers between 1 and 5 are:
4"
If I could get some feedback on what I'm doing wrong here, it'd be appreciated. Thanks
//Declare variables
int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 ==0)
{
System.out.println(count);
}
count++;
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
} //end loop
create an int array or Collection before your loop, when you find out the even number in while loop, append the number in the array/collection.
After the while loop, print output only once, of course with those found numbers.
I think it is straightforward, and I leave the implementation part to you.
You should take last part of the while loop out of it:
//Part B
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
int count = n1;
while (count < n2) {
if (count % 2 ==0) {
System.out.print(" " + count);
}
count++;
}
As you didn't mention that you want a comma between even numbers, then replacing println with print should be enough
They are different ways to achieve your goal. A quick solution would be to put
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
in front of your while-loop and and replace System.println() with System.print().
int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
System.out.print("Even integers between " + n1 + " and " + n2 + " are: ");
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 == 0)
{
System.out.print(count);
}
count++;
} //end loop

Math.random won't randomize number 9 whenever it has to be assigned to last array slot

My code creates an array of size 10, it randoms numbers from 0 to 9 to fit in each slot. The problem comes when the number 9 is not picked until the last space. Math.random keeps randomizing numbers but it will never pick the number 9. I ran the program for about 1 minute and it never picked it.
Here is my program
public class GenerateRandomNumbers{
// main method
public static void main(String[] args) {
int aSize = 10;
int[] a = new int[aSize];//setting size of array
for(int i = 0; a.length > i; i++){//looping through the whole array
a[i] = (int)(Math.random()*9) + 1;//assigning random number to each slot of array
System.out.println("assign " + a[i] + " to i" + i);
//looping through filled array slots.
for(int k = i-1; -1 < k; k--){
System.out.println("Check if " + a[i] + " i"+ i + " = " + a[k]+ " k"+ k );
//if not unique give a new number
if(a[i] == a[k]){
System.out.println("CHANGE HERE");
a[i] = (int)(Math.random()*9) + 0;
System.out.println("assign " + a[i] + " to " + i);
k = i;//reset loop so it checks all over again
}
}
System.out.println("ACCEPT");
}
for(int i = 0; a.length > i; i++){
System.out.println(a[i]);
}
}
}
Can someone explain me what is causing the bug?
Your line a[i] = (int)(Math.random()*9) + 0; is different from the time you used Math.random() above. Above you said (int)(Math.random()*9) + 1, that will give you a random number in the range of [1,9].
(int)(Math.random()*9) + 0 will never evaluate to 9, its range is [0,8].

How to return a single print statement from a search() method in an array?

I'm having trouble with my search method. What I want to do is have my search method print the statement only once. So if my array contains "3" more than once, I only want to print "3 was found." once instead of checking each value and reporting that there is or is not a "3" at that point in the array. How would I do that?
To clarify, this is what I have:
`0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was found.
2 was not found.
2 was not found.`
And this is what I want:
0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was found.
2 was not found.
So this is my complete class. I created a method called initialize that will assign each element in my array a random integer between 0 and 10; a method called print to print out the contents of my array; a method called printStats to find and then print the average, maximum, and minimum value in my array; and a method called search that searches my array (and prints the result) for an integer parameter passed to my method.
Everything works correctly.
public class ArrayLab
{
private int[] array;
public ArrayLab(int numElements)
{
array = new int[numElements];
}
public void initialize()
{
array[0] = (int) (Math.random()*11);
array[1] = (int) (Math.random()*11);
array[2] = (int) (Math.random()*11);
array[3] = (int) (Math.random()*11);
array[4] = (int) (Math.random()*11);
array[5] = (int) (Math.random()*11);
array[6] = (int) (Math.random()*11);
array[7] = (int) (Math.random()*11);
array[8] = (int) (Math.random()*11);
array[9] = (int) (Math.random()*11);
}
public void print() {
System.out.println(array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "," + array[4] + "," + array[5] + "," + array[6] + "," + array[7] + "," + array[8] + "," + array[9]);
System.out.println();
}
public void printStats()
{
double sum = 0;
int max = 0;
int min = 0;
min = array[0];
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
double average = sum/array.length;
System.out.println("Average Value: " + average);
System.out.println("Maximum Value: " + max);
System.out.println("Minimum Value: " + min);
}
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
}
else
{
System.out.println(numChosen + " was not found.");
}
}
}
}
Start using return or break statement to break the loop after you hit the first successful search.
Also, you should not print the Was Not Found every time while iterating the array. You should print it only once in the end when your array gets exhausted completely and search query is not found.
Here is the modified code snippet:
boolean flag = false;
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
flag = true;
break;
}
}
if(!flag) {
System.out.println(numChosen + " was not found.");
}
Alternatively, you can also do the following:
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
Well, you don't need to keep iterating through the loop once you found the number. Also, you want to print "was not found" in a case it didn't find anything, meaning the loop finished without printing anything yet.
So this is how you should implement it:
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
}
In a case it found something, it will print the message and exit the method and never reach the printing of second message. It will only print the second message when the loop is over.
You are displaying results in your public void search(int numChosen) function. In your case, instead of printing every time you encounter a match, put a counter instead, then print once: that counter with the rest of you sentence.
Try this:
public void search(int numChosen)
{
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == numChosen)
count++;
if (count == 0)
System.out.println(numChosen + " was not found.");
else
System.out.println(numChosen + " was found " + count + " times.");
}

How to compare the given integer with possible roots

I could not name the question in the best way... My aim is to write a program that takes integer n from user. Then compare with the third power of two integers a and b.
If a^3 + b^3 is smaller than or equal to the given input, I want to print out every single possible calculation to the user.
My code is as follows:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
When I run this and give an input as 30, it prints
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
What am I doing wrong?
You increase j and i twice. That's why you test only the even values for i, j.
If you want to correct the code, remove the i++, j++ from the end and use only the increments from the 2 fors.

Categories