Java - Cant get it to work - java

I have been trying to finish this for a couple of hours now. My program is supposed to generate random numbers due to the users input. Then the program divide the numbers in two new even and odd arrays. I have solved the "generated random numbers" part but now i need too transfer the even and odd numbers into two new arrays.
This is what the output should look like:
How many random numbers between 0 - 999 do you want? **12**
Here are the random numbers:
145 538 56 241 954 194 681 42 876 323 2 87
These 7 numbers are even:
538 56 954 194 42 876 2
These 5 numbers are odd:
145 241 681 323 87
This is my code at the moment:
import java.util.Scanner;
public class SlumpadeTal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
}
}
}
}
NOTE that i can't use any class for this. such as Arraylist, Vector or others!

A simple solution would be to count to number of even numbers and odd numbers,
create arrays of those sizes, and once again iterate over your original array to put each number in it's place.
edit: something like this:
int evenCounter = 0;
int oddCounter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
evenCounter++;
}
else
oddCounter++;
}
}
int[] evenArray = new int[evenCounter];
int[] oddArray = new int[oddCounter];
evenCounter = 0;
oddCounter = 0;
for (int i =0; i < arrayen.length; i++){
if ((arrayen[i] % 2) == 0) {
evenArray[evenCounter] = arrayen[i];
evenCounter++;
}
else{
oddArray[oddCounter] = arrayen[i];
oddCounter++;
}
}

My solution will be divide the number into odd or even number after a number is generated. Using arraylist will be better than array because its capacity will be grow automatically and it is suitable for your case because you dont know how many even number or odd number will be generate for each time.

The if-statement you have in your code (if ((arrayen[i] % 2) == 0)) is correct.
What I suggest doing is instead of creating new arrays, create a collection type that has a dynamic length, such as an ArrayList. That way you don't have to worry about figuring out the size first, and thus don't have to iterate twice.
If you really need an array for whatever reason, you can always convert the ArrayList to an array with ArrayList#toArray(T[])

Related

Java code to find polygonal numbers based on input

I need a program that can do following example:
"What is the number of sides of your polygon?" "3"
"How many of these would you like to see?" "36"
"1 3 6 10 15 21 28 36 45 55"
"66 78 91 105 120 136 153 171 190 210"
"496 528 561 595 630 666"
-It has to be able to input the values from the first two questions and print then answers off 10 to a line. I've tried writing the code myself but constantly get stuck in the for loop.Thank you.
This is what I have so far:
Scanner input = new Scanner(System.in);
//Request number of sides the polygon must have
System.out.println("What is the number of sides of your polygon? ");
n = input.nextInt();
System.out.println("How many of these would you like to see? ");
k = input.nextInt();
long output = polygonalNumber(n,k);
for (k = 1; k < k; k++);
if (output % 10 == 0) {
System.out.println();
}
}
public static long polygonalNumber(long n, long k){
long p = (k * k) * (n-2) - (k * (n-4))/2;
return polygonalNumber(n,k);
Your code looks really messed up. But no worries, I wrote a version that supports from 3-6 sides.
Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Request number of sides the polygon must have
System.out.println("What is the number of sides of your polygon? ");
int sides = input.nextInt();
System.out.println("How many polygonal numbers do you want?");
int amount = input.nextInt();
input.nextLine();
input.close();
FindPolygonalNumbers(sides, amount);
}
static void FindPolygonalNumbers(int sides, int amount) {
String numbers = "";
for (int i = 1; i <= amount; i++) {
int number = 0;
if (sides == 3) {
number = (i * (i + 1)) / 2;
} else if (sides == 4) {
number = i * i;
} else if (sides == 5) {
number = (3 * i * i - i) / 2;
} else if (sides == 6) {
number = i * (2 * i - 1);
}
numbers = numbers + number + ", ";
}
System.out.println(numbers);
}
If you have any questions regarding the code, don't hesitate to ask about it.

Java print multiple lines after reading multiple lines

(It's my homework task. So I can't make any changes to the task like changing the rules of input.)
I need to calculate
a^m mod n
and print out the result. (I've already figured out how to code the calculation.)
But the question said there'll be multiple lines of input:
IN:
12 5 47
2 4 89
29 5 54
and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)
OUT:
14
16
5
The code I've tried so far:
import java.util.Scanner;
public class mod {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int count = 0;
while (input.hasNextLine()){
count++;
}
int[] array = new int[count];
for (int i = 0; i < count; i ++){
int a = input.nextInt();
int m = input.nextInt();
int n = input.nextInt();
int result = (int)((Math.pow(a, m)) % n);
array[i] = result;
}
for (int x : array){
System.out.println(x);
}
}
}
I tried to count the lines of input and build an array of that size to store the results.
But it seems my code fail to detect the end of input and keep looping.
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
} else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
lines.add(line);
}
}
int count = lines.size();
for (int i = 0; i < count; i++) {
String[] tokens = lines.get(i).split("\\s+");
int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
n = Integer.parseInt(tokens[2]);
int result = (int) ((Math.pow(a, m)) % n);
System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
I tested with your provided input,
12 5 47
2 4 89
29 5 54
(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5

generation of random output 3n+1 pblm

I have been trying to solve the 3n+1 question in java.However my output seems to be very random. The question is
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then tex2html_wrap_inline44
5. else tex2html_wrap_inline46
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
The Input
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
My code is as given below
class CC
{
int c,f,l,m;
int returnCount(int i,int j)
{
f=0;
for(int k=i;k<=j;k++)
{
l=k;
c=0;
while(l>1)
{
if(l%2==0)
{
l=l/2;
c++;
}
else
{
l=3*l+1;
c++;
}
}
if(f<c)
f=++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j;
CC obj=new CC();
while(sc.hasNextInt())
{
i=sc.nextInt();
j=sc.nextInt();
System.out.println(i+" "+j+" "+obj.returnCount(i,j));
}}}
Now my Input is
605293 606510
956739 956006
826611 825983
756134 756776
478642 479101
815892 815933
719220 719135
929349 929040
And expected output is
605293 606510 341
956739 956006 352
826611 825983 313
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 274
929349 929040 339
However my output is
605293 606510 341
956739 956006 0
826611 825983 0
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 0
929349 929040 0
Please help me find the mistake
The problem is that your in your first line the first number is smaller than the second one, but in the second line the first number is bigger than the second one. You have to switch the numbers or find out the bigger one upfront like that:
import java.util.Scanner;
public class CC {
int c, f, l, m;
int returnCount(int i, int j) {
int smaller = Math.min(i, j);
int bigger = Math.max(i, j);
f = 0;
for (int k = smaller; k <= bigger; k++) {
l = k;
c = 0;
while (l > 1) {
if (l % 2 == 0) {
l = l / 2;
c++;
} else {
l = 3 * l + 1;
c++;
}
}
if (f < c)
f = ++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, j;
CC obj = new CC();
while (sc.hasNextInt()) {
i = sc.nextInt();
j = sc.nextInt();
System.out.println(i + " " + j + " " + obj.returnCount(i, j));
}
}
}
The input and output looks then like that:
956739
956006
956739 956006 352

Equal Spacing In print statements

So I was just about finished with a small little program and when I ran it everything worked fine. I did have 1 small technical issue that I didnt like and it was an unevenly spaced "table" if you would. In a nutshell I want it so my outputs are aligned on both sides.
Original output:
How many numbers should be generated?
10
What is the number of values of each random draw?
1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
Code:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}
Take a look at the System.out.format (https://docs.oracle.com/javase/tutorial/essential/io/formatting.html) and in perticular the width option. This is probably what you are wanting.
Two ways to go about this:
1) As stated already, look at the System.out.format directory. It has a wide availability of methods to format your output
2) Change the spacing in a manual way, where the spacing depends on the amount of characters in the number to the left.

To produce an random output: 100 numbers from 901 to 999

I'm trying to create two separate outputs of 10 columns and 10 rows of numbers. I know I can do the first output using numbers 4 through 7 and the second output using numbers 10 through 90. But I have in trouble to do the third output using numbers 901 through 999. Below is the Java code I have:
import java.util.Random;
public class LabRandom
{
private static final Random rand = new Random();
public static void main(String[] args)
{
int number;
int i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(4) + 4);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(9)*10+10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
System.out.println();
i = 1;
while (i <= 100)
{
//number = rand.nextInt(4) + 4;
System.out.printf("%-5d", rand.nextInt(100)*10);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
}
}
I'm having trouble understanding what you want. If you want to create an output of 100 randomly chosen number in the range 900 to 999, with line breaks after every 10 such numbers, try adding this loop to your code:
i = 1;
while (i <= 100)
{
// generate a random number from 0 to 100-1,
// then add 900 to transform the range to 900 to 999
System.out.printf("%-5d", rand.nextInt(100) + 900);
if (i % 10 == 0)
{
System.out.println();
}
i++;
}
By the way, if you really want to print numbers 10 to 90, your second loop is incorrect.
Right now you print multiples of 10, from 10 to 90, eg 10,20,30.....90
For every number between, you would want:
rand.nextInt(80)+10
// difference between the highest and the lowest value you want to have in your result
int range = 99;
// the lowest possible value you want to see in your result
int lowestValue = 901;
//note that you will never get the numbers 900 and 1000 this way, only between
int result = rand.nextInt(range) + lowestValue;
You might want to read what exactly nextInt(value) does (easy to do inside a proper IDE since it will provide JavaDoc tooltip, which is of course available and well detailed in such general Java classes).

Categories