How do I fix my java program not stopping running? - java

I am writing a simple program as some practice for Java. It takes in integers and puts them into a two-dimensional array of R rows and C columns and then simply prints out each element of the array (just for troubleshooting). When I run the code it prints every integer like it should but the program does not stop running. I have to force stop it. Why is it not stopping on its own? I tried some basic debugging and tried to see if I accidentally had an infinite loop in the code but I couldn't find it.
In case it is important I am using IntelliJ Idea Ultimate 2019.3.
Thanks
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt(); //Takes number of test cases
for(int i = 1; i <= T; i++){ //This is the counter for each test case
int R = in.nextInt(); //R is # of rows
int C = in.nextInt(); //C is # of columns
int K = in.nextInt(); //K is the thickness allowed
int numArray[][] = new int[R+1][C+1];
for(int j = 0; j < R; j++){
for(int k = 0; k < C; k++){
numArray[j][k] = in.nextInt();
System.out.println(numArray[j][k]);
}
}
}
in.close();
}//End of main
}//End of main class
Edit: Just for future reference I will include the input and the output I was getting.
Input:
3
1 4 0
3 1 3 3
2 3 0
4 4 5
7 6 6
4 5 0
2 2 4 4 20
8 3 3 3 12
6 6 3 3 3
1 6 8 6 4
Output:
3
1
3
3
4
4
5
7
6
6
2
2
4
4
20
8
3
3
3
12
6
6
3
3
3
1
6
8
6
(and here the cursor is stuck blinking not doing anything and the program doesn't quit on its own)
I solved the issue by manually typing the input instead of copying and pasting it. Not sure what caused that issue but it worked!

This little piece of code requires the user to input 3 integers (R, C and K) T-times:
int T = in.nextInt();
for(int i = 1; i <= T; i++){
int R = in.nextInt();
int C = in.nextInt();
int K = in.nextInt();
// ...
}
Additionally the user has to input an integer R*C-times until i <= T:
for(int j = 0; j < R; j++){
for(int k = 0; k < C; k++){
numArray[j][k] = in.nextInt(); // << requires user-interaction each loop here >>
System.out.println(numArray[j][k]);
}
}
If you use T=1, R=1, C=1, K=1 the user has to input only 1 additional integer, as there is only 1 test-repitition and R*C = 1. With that your program terminates just as expected.
With bigger values of T, R, C, K the required user-interactions grow exponentially, which probably makes you think that your program should have ended but it still waits for additional user-input.

Ok I think I figured out the issue. I was copying and pasting the test inputs from a web page. I tried double checking to make sure the input was valid and then inputting them by hand and it fixed it. Not 100% why but that fixes the problem. Thanks for the help!

your for(int i = 1; i <= T; i++) probably newer ends because you are increasing T.
You need to made some condition in loop to exit. For example
if (xx == yy) break;

Related

Arithmetic Progression in java

i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}

How do you print the sequence one 1, then two 2, three 3, ... n ns?

Write a program that prints a part of the sequence:
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...
(the number is repeated as many times, to what it equals to).
I've used two for loops, however, I can't get 1 to print once, 2 to print twice, instead, I get
1 2 3 4 5 6 1 2 3 4 5 6, etc.
You need two for loops for this.
for (int i = 0; i <= 5; i++) { // This will loop 5 times
for (int j = 0; j < i; j++) { //This will loop i times
System.out.print(i);
}
}
As I remember the goal is to print n numbers (for example 1 2 2 3 3 3 4 for n = 7), diveded by space. Sorry for my java)), I wrote it in Kotlin, tried to change for Java, but main idea is clear. BTW n – the number of the elements, you need to read with Scanner.
int count = 0 //Idea is to create a counter, and to increment it each time of printing
for (int i = 0; i <= n; i++) { //Loops n times
for (int j = 0; j < i; j++) { //Loops i times
if (int count < int n) {
System.out.print(" "+i+" ");
int count++ //Prints 1 one time, 2 two times, etc. stops if reached n number
}
}
}
How about this :
for(int i=1;i<=num;i++){
for(int j=1;j<=i;j++){
System.out.print(" "+i+" ");
}
}
where, num = 1,2,....n
(Also we wont be able to tell why you got that output unless you attach the code. Please attach the code snippets for such questions :) !

3 Dice Sum Counting Program Java

For my Computer Science Class, my teacher is asking us to do the following:
Program Description: You are learning to play a new game that involves 3 six-sided die. You know that if you knew the probability for each of the possible rolls of the die that you’d be a much better competitor.
Since you have just been studying arrays and using them to count multiple items that this program should be a snap to write. This will be cool since the last time we did this we work just looking for how many times 9 or 10 could be rolled and this program won’t require any if statements.
Required Statements: output, loop control, array
Sample Output:
Number Possible Combinations
1 0
2 0
3 1
4 3
5 6
6 10
7 15
8 21
9 25
10 27
11 27
12 25
13 21
14 15
15 10
16 6
17 3
18 1
I can easily do this with an if statement, but I don't understand how to do it without one. It is especially tricky because under hints, she wrote: "These programs utilize a counting array. Each time a value is generated the position at that index is incremented. It’s like the reverse of the lookup table." I have no idea what this means.
Here's my code with the if statement:
public class prog410a
{
public static void main(String args[])
{
System.out.println("Number\tPossible Combinations");
for (int x = 1; x <= 18; x++)
{
int count = 0;
for (int k = 1; k <= 6; k++)
{
for (int i = 1; i <= 6; i ++)
{
for (int j = 1; j <= 6; j++)
{
if (k + i + j == x)
count++;
}
}
}
System.out.println(x + "\t\t\t" + count);
}
}
}
So I guess my overall question is this: How can I emulate this, but by using some sort of array instead of an if statement?
You don't need the outer x loop. All you need is three nested loops, one for each die. You will also need an array of integers all initialized to zero. Inside the innermost dice loop, you just use the sum of the three dice as the index to you integer array and increment the value at that index.
After you complete the dice loops, then you can iterate over your integer array and output the frequency of your results.
Since this is homework, I won't write the code for you, just give you the general outline.
Create a count array of size 18. Initialise all values to 0.
Have three nested loops counting from 1 to 6 exactly like your three inner loops. These represent the values on your dice.
Inside your innermost loop, add the three loop counters together. This is your dice total and you use it as an index into the count array to increment the value at that index.
After you exit the three nested loops, use another loop to iterate through the count array to print out the values.
This seems to work - and without if:
public void test() {
// Remember to -1 because arrays are accessed from 0 to length-1
int[] counts = new int[18];
// Dice 1.
for (int k = 1; k <= 6; k++) {
// Dice 2.
for (int i = 1; i <= 6; i++) {
// Dice 3.
for (int j = 1; j <= 6; j++) {
// Count their sum (-1 as noted above).
counts[i + j + k - 1] += 1;
}
}
}
// Print out the array.
System.out.println("Number\tPossible Combinations");
for (int i = 0; i < counts.length; i++) {
System.out.println("" + (i + 1) + "\t" + counts[i]);
}
}
Essentially you build the results in an array then output them.
From Wikipedia: In computer science, a lookup table is an array that replaces runtime computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than undergoing an 'expensive' computation or input/output operation., this means that usually we use lookup tables to save computation time by precalculating some process into a table in which we already stored the result. In this case you are using the process to store the number of possible outcomes in an array. Basically you are building a lookup table for the dice outcome. Only the three inner loops are needed.
for (int k = 1; k <= 6; k++)
{
for (int i = 1; i <= 6; i ++)
{
for (int j = 1; j <= 6; j++)
{
arr[k + i + j-1] = arr[k + i + j-1] +1;
}
}
}
And this is what is happening:
dices index
i j k (i+j+k)
1 1 1 3
1 1 2 4
1 1 3 5
1 1 4 6
1 1 5 7
1 1 6 8
1 2 1 4
1 2 2 5
1 2 3 6
1 2 4 7
1 2 5 8
1 2 6 9
1 3 1 5
1 3 2 6
.
.
.
You are enumerating each possible outcome and then adding the spot in the array with the index generated. When the nested loops are done, you will have an array containing the desired information.

For loop to print the number in sequence and reverse it

How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}

How to make a java program with output a triangle of numbers?

I understand that there is a similar post to this one, but based on the answers I can not both apply the answers to my current class, or understand the rest of the answers.
I need to create a program using nested "for loops" that creates an output like this one (just symmetrical). I have been trying to get this to work for two whole evenings now, and can't figure it out...
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I would GREATLY appreciate any help!!!
public class PyramidOfDoom {
public static void main(String[] args)
int k = 2;
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
} else {
System.out.print(k);;
}
}
System.out.println();
}
}
}
I thinks it can be done in simple steps as 1. print leading spaces 2. print increasing numbers 3. print decreasing number 4. print trailing spaces 5 print new line.
Sample code(concept) as below.
int row = 10;
for(int i=1; i<=numRow ; i++){
int num = 1;
for(int j=0; j<numRow- i; j++ ){
System.out.print(" ");
}
for(int j=numRow-i+1; j<=numRow ; j++ ){
System.out.print(num+" ");
num=num*2;
}
num=num/2;
for(int j=numRow+1; j<numRow+i; j++ ){
num=num/2;
System.out.print(num+" ");
}
for(int j=numRow+i+1; j<=numRow*2; j++ ){
System.out.print(" ");
}
System.out.print("\n");
}
You're not changing k at all. You need to keep multiplying it by 2 until you get to the middle of the row, then start dividing it by 2. As it stands, in your System.out.println(k), how can you expect it to print anything but 2 if you never manipulate it? :)
Also, you have two semicolons in your System.out.println(k);;. That seems odd to me, but I suppose it actually makes sense that it would compile.

Categories