I want to move cursor up to the beginning after it wrote something at lower part. I mean is there something like SetCursorPosition(0,0)?
edit: it is about writing 6x3 matrix with numbers in it. it should be seem like this
...
7 8 9
4 5 6
1 2 3
it'll start write from bottom. when the cursor at (0,0) it'll put 6x space then write 1 2 3, then go to (0,0), put 5x space, write 4 5 6 ...
code:
boolean sa;
int yoyo;
int lo = 18;
int y = 0;
for (int k = 1; k < 100; k++)
{
if (y < 18)
{
sa = true;
for (int h = 2; h < k; h++)
{
if (k % h == 0)
sa = false;
}
if (sa)
{
lo--;
if (y % 3 == 0)
{
yoyo = lo / 3 + 1;
// here where I need Console.SetCursorPosition(0,0)
for (int yos = 0; yos < yoyo; yos++)
{
System.out.print("\n");
}
if (k < 10)
System.out.print(" " + k + " ");
else
System.out.print(k + " ");
}
else
{
if (k< 10)
System.out.print(" " + k + " ");
else
System.out.print(k + " ");
}
y++;
}
}
}
Unfortunately, Java doesn't have full console support.
You might try JLine.
I asked the developers of JLine and you can set the cursor position using this.
terminal.puts(InfoCmp.Capability.cursor_address, 0, 0);
Here's a small example of it's usage and as an added bonus I'll show how to make the cursor invisible and visible.
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.InfoCmp;
import java.io.IOException;
public class CursorStuff
{
public static void main(String[] args) throws IOException, InterruptedException
{
int row = 10;
int col = 40;
Terminal terminal = TerminalBuilder.terminal();
terminal.puts(InfoCmp.Capability.cursor_address, row, col);
System.out.println("Here we start at row " + row + " col " + col);
System.out.println("Now you see the cursor");
Thread.sleep(2000);
terminal.puts(InfoCmp.Capability.cursor_invisible);
System.out.println("Now you don't!");
Thread.sleep(2000);
terminal.puts(InfoCmp.Capability.cursor_visible);
System.out.println("And the cursor is back again.");
}
}
Make sure to have either Jansi or JNA in your libraries otherwise you will get a dumb terminal and not be able to use these functions at least on Windows as it requires these to do native function calls.
As far as I can tell this is the easiest method to accomplish this as before I knew this was an option I was writing C++ and calling those native function calls I made using JNI.
Related
Closely related to Java programming - nested for loops for minesweeper game, my Minesweeper program is designed to loop through cells, check each adjacent cell, perform a logic test to check if it's a Mine, and then jump to the next one. However, when I run it, it somehow becomes an infinite loop. I've tried changing variables, reversing signs (< becomes > and + becomes -), and googling other solutions, but I can't find anything.
Printouts are for debugging, gameboard is set to [10][10],
public static void assignNumbers(int[][] gameBoard)
{
for(int r = 0; r <= (gameBoard.length - 1); r++){ //row
for(int c = 0; c <= (gameBoard[0].length - 1); r++){ //column
System.out.print("New Cell ");
for(int vR = r+1; vR > r-2; vR --){ //vR is visiting Row
for(int vC = c+1; vC > c-2; vC --){ //vC is visiting Column
System.out.print("new item ");
if (isValid(vR, vC, gameBoard)){
System.out.print("isMine? ");
if (isMine(vR, vC, gameBoard)){
gameBoard[r][c] += 1;
System.out.print(" MINE ");
}
else {
System.out.print(" NO ");
}
}
}
}
System.out.println();
}
}
}
public static boolean isMine(int r, int c, int[][] gameBoard){
if(gameBoard[r][c] != 100){
return false;
}
else{
return true;
}
}
public static boolean isValid(int r, int c, int[][] gameBoard)
{
// Returns true if row number and column number
// is in range
return ((r >= 0) && (r < SIDE)) && ((c >= 0) && (c < SIDE)) && !isMine(r, c, gameBoard);
}
When I try to run it, I get an infinite printout saying :
"New Cell" followed by 9 "new items". This should only print out 100 times (once for each cell), however it doesn't stop after 100. I assume it's a logic error in one of the for loops, but I can't find it for the life of me. Any help is appreciated, and I'll do my best to answer any questions.
EDIT: punctuation
Try to replace r++ with c++
for(int c = 0; c <= (gameBoard[0].length - 1); c++){ //column
I have this project that I have been working on, but I'm a bit rusty so I could use some help to figure out this part.
The main jizt of my project, is that I want to be able to fire a gun at a target and have the target analyze my data.
Before I even start on this, I did some research to find out if anyone else had done this before, and turns out a company in USA have done it, but in a different way than what I imagined..
This is not meant as a business idea, just a fun project for my self :)
Now here is my issue, I ofcourse made a "prototype" without the gun, and without the targets.
All text in Java to see if I could make this work.
I researched a bit since I was rusty (and still am), and figured out most of the problems I faced.
The part that has me stuck is at the very end of it, I have an array for all the shots but I want to divide this array into multiple arrays with the size of the magazine capacity.
How would I accomplish this?
Unfortunately I don't save my code, if I chose to delete it, so my scraps are long gone, but I have tried a few things that came to mind and for several days I havn't been able to figure this one out..
I tried with nested for loops, then I tried again but with nested for loops in a while loop, and I probably tried a few different things aswell.
if (hasrun == true) {
//OUTPUT
ms(2);
System.out.print("You shot the following:");
nl(1);
int counter = 0;
int i = 0;
while (sf > magcap) {
sf-=magcap;
mnm++;
}
while (counter <= mnm) {
System.out.print("Mag " + mn + ": ");
for (i+=0; i < magcap; i++) {
System.out.print(shots[i] + " ");
}
counter++;
mn++;
nl(1);
}
Just to clarify some things in my code here, I know this isn't the cleanest code, I'm not going for clean, and I know I don't need half of my functions (methods), but I did them to practice so they're there. Any help would be greatly appreciated with solving my problem tho! :)
If you want to have a look at all of my code for this project, head over to pastebin
You can use Guava to do it easily,
int[] x = {1,2,3,4,5,6};
int splitSize = 3;
List<Integer> list = IntStream.of(x).boxed().collect(Collectors.toList());
//partition
List<List<Integer>> partitioned = Lists.partition(list, splitSize);
//result: [[1,2,3], [4,5,6]]
Using System.arraycopy:
import java.util.Arrays;
public class Testing {
// static int[] input = {1,2,3,4,5,6}; // testdata
static int[] input = {1,2,3,4,5,6,7}; // testdata
// static int[] input = {1,2,3,4,5,6,7,8}; // testdata
static int magSize = 3; // testdata
// static int magSize = 5; // testdata
public static void main(String[] args) {
// int resultSize = (int) Math.ceil((double) input.length / magSize);
int resultSize = input.length % magSize == 0 ?
input.length/magSize :
input.length/magSize + 1;
int[][] result = new int[resultSize][magSize];
for (int i = 0; i < resultSize; i++) {
System.arraycopy(input, // src
i*magSize, // srcPos
result[i], // dest
0, // destPos
(i + 1) * magSize < input.length ?
magSize :
input.length - i*magSize); // length
}
System.out.println("Original : " + Arrays.toString(input));
System.out.println("Result : " + Arrays.deepToString(result));
/*
prints:
Original : [1, 2, 3, 4, 5, 6, 7]
Result : [[1, 2, 3], [4, 5, 6], [7, 0, 0]]
*/
}
}
I figured it somewhat out, here is what I did. Not quite implemented yet, but this worked with an array.
// OUTPUT
while (sf >= magcap) {
sf -= magcap;
mn++;
}
ms(2);
System.out.println(mn + " mags and " + sf + " shots fired");
nl(2);
for (int i = 0; i < mn; i++) {
from = magcap * magcounter - magcap;
to = magcap * magcounter;
System.out.print("Mag " + magcounter + ": ");
for (int j = from; j < to - 1; j++) {
System.out.print(shots[j] + ", ");
}
System.out.print(shots[to - 1] + ".");
magcounter++;
nl(1);
}
// PRINT THE REST
if (sf >= 1) {
from = magcap * magcounter - magcap;
to = magcap * magcounter;
if (sf == 1) {
System.out.print("Mag " + magcounter + ": ");
System.out.print(shots[from] + ".");
} else {
System.out.print("Mag " + magcounter + ": ");
for (int i = 0; i < sf - 1; i++) {
System.out.print(shots[from + i] + ", ");
}
from += sf -1;
System.out.print(shots[from] + ".");
}
}
The output is
1 2 3 4 5 6 7 8 9 10
3 mags fired and 1 shots fired
Mag 1: 1 2 3
Mag 2: 4 5 6
Mag 3: 7 8 9
Mag 4: 10
I am trying to make a connect 4 program in java and I am stuck on the winner check. I know that I could make a very long list of if and else if's but I think loops would work better. I'm open to any other way of solving this problem but on what I've been looking at makes it seem the best. I have an idea of what to do with the rows and columns but I don't even know where to start with the diagonals. This is what I have so far:
edit:
int p1counter = 0;
int p2counter = 0;
int r = 1;//x
int c = 1;//y
for(r = 1; r <= 6; r++)
{
while(c <= 7)
{
if(grid[r][c].equals("_"))
{
c++;
p1counter = 0; p2counter = 0;
}
else if(grid[r][c].equals("1"))//player 1 counter
{
c++;
p1counter++;
}
else if(grid[r][c].equals("2"))//player 2 counter
{
c++;
p2counter++;
}
}
if(p1counter >= 4)
{
JOptionPane.showMessageDialog(null, "Player 1 is the winner!");
done = true;
}
else if(p2counter >= 4)
{
JOptionPane.showMessageDialog(null, "Player 2 is the winner!");
done = true;
}
return done;
}
In similar situations I have done the following:
Create an array of strings; as many strings as there are rows+columns+diagonals
Traverse the grid in the four possible directions (this does not include every possible diagonal since diagonals must be at least 4 long) and enter a corresponding character in the string: for example 0 (empty), 1, 2
Search the string array for 1111 and 2222.
By first organizing the data, the comparison can be done with a built in function. Much faster and cleaner.
Here is how it might be done (this is the "slow and careful way"):
class c4check {
public static void main(String[] args) {
char grid[][] = {{'e','e','e','e','a','b','a'},
{'e','a','b','a','b','b','a'},
{'e','b','a','a','b','b','a'},
{'e','a','b','b','a','b','b'},
{'e','b','a','b','b','a','a'},
{'e','a','b','a','b','b','a'}};
int ii, jj, ri, ci, di;
String checkGrid[] = new String[25];
// copy rows:
for(ri = 0; ri < 6; ri++) {
String temp = "";
for(ci = 0; ci < 7; ci++) {
temp += grid[ri][ci];
}
checkGrid[ri] = temp;
}
// copy columns:
for(ci = 0; ci < 7; ci++) {
String temp = "";
for(ri = 0; ri < 6; ri++) {
temp += grid[ri][ci];
}
checkGrid[ci + 6] = temp;
}
// copy first diagonals:
for(di = 0; di < 6; di++) {
String temp = "";
for(ri = 0; ri < 6; ri++) {
ci = di - 2;
ri = 0;
while(ci < 0) {
ri++;
ci++;
}
for(; ri < 6; ri++, ci++) {
if( ci > 6 ) continue;
temp += grid[ri][ci];
}
}
checkGrid[di+13] = temp;
}
// diagonals in the other direction:
for(di = 0; di < 6; di++) {
String temp = "";
for(ri = 0; ri < 6; ri++) {
ci = 8 - di;
ri = 0;
while(ci > 6) {
ri++;
ci--;
}
for(; ri < 6; ri++, ci--) {
if( ci < 0 ) continue;
temp += grid[ri][ci];
}
}
checkGrid[di+19] = temp;
}
for(ii = 0; ii < 25; ii++) {
System.out.println("Checking '" + checkGrid[ii] + "'");
if (checkGrid[ii].contains("aaaa")) System.out.println("Player A wins!");
if (checkGrid[ii].contains("bbbb")) System.out.println("Player B wins!");
}
}
}
Obviously, instead of copying temp to an array element, and then checking at the end, you could check for "aaaa" or "bbbb" each time, and return from the function as soon as you found a match.
Output of this particular code (which has more than one "winning" combination, so it's not a "real" situation - but it allowed me to check that all the diagonals were visited correctly):
Checking 'eeeeaba'
Checking 'eababba'
Checking 'ebaabba'
Checking 'eabbabb'
Checking 'ebabbaa'
Checking 'eababba'
Checking 'eeeeee'
Checking 'eababa'
Checking 'ebabab'
Checking 'eaabba'
Checking 'abbabb'
Checking 'bbbbab'
Player B wins!
Checking 'aaabaa'
Checking 'eaaa'
Checking 'ebbbb'
Player B wins!
Checking 'eaabbb'
Checking 'ebaaaa'
Player A wins!
Checking 'eabba'
Checking 'ebbb'
Checking 'abba'
Checking 'ababb'
Checking 'abbbaa'
Checking 'bbabbe'
Checking 'aaaae'
Player A wins!
Checking 'ebbe'
Here is way to maintain the track of winner :-
maintain 4 types of sets (horizontal,vertical,two diagonal).
whenever a point on grid is colored check with corresponding neighbour in the same type eg. if grid point (x,y) is colored then for horizontal type we check (x,y+1) and (x,y-1).
find union of two similar colored neighbour.
If size of any set is equal to four then you have found the winner. You can check while updating neighbours of point currently colored.
Suggestions: Use Union-Find datastructure to achieve good time complexity (Note as your sets are small you can do without it as well).
Trying to write a simple program that prints the Fibonacci sequence. I want to create a method named fibNumber that calculates the value of the Fibonacci sequence and then I want to use a for loop in the run() method to print that value 15 times. The trouble I'm having is the println method in the for loop. Eclipse says "n cannot be resolved to a value" and "i cannot be resolved to a value." I thought I covered all the bases in terms of declaring the variables. Am I missing something?
What I want to write is all the way up to F15
F0 = 0
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
import acm.program.*;
public class FiccononicSequence extends ConsoleProgram {
public void run(){
println("This program prints out the Fibonacci sequence.");
for (i = 1; i <= 15; i++){
println("F" + i + " = " + fibNumber(n));
}
}
private int fibNumber(int n){
if (n == 0){
return 0;
}else{ if (n == 1){
return 1;
}else{
return fibNumber(n - 1) + fibNumber(n - 2);
}
Try this...
- The problem here is about the scope of the variable.
- i should be declared of type int, which is local to the run() method instead of n, as n is another local variable in fibNumber() method.
- i and n are totally in different scope and are invisible to each other.
for (int i = 1; i <= 15; i++){
println("F" + i + " = " + fibNumber(i)); // i should be here.
}
Whats "n"? You should probably be using "i" instead of "n" there.
The problem is how you call the fibnumber method, because the n variable isn't declared anywhere in the run method context:
for (int i = 1; i <= 15; i++){
println("F" + i + " = " + fibNumber(n)); //what's n?
}
To fix it, just send the i variable:
for (int i = 1; i <= 15; i++){
println("F" + i + " = " + fibNumber(i)); //now it compiles!
}
You need to define i in the for loop and pass it to fibNumber
for (int i = 1; i <= 15; i++){<-- Define i
println("F" + i + " = " + fibNumber(i));<-- pass `i `
}
I'm sure I'm making a rookie mistake with java(this is actually my first program). I am trying to port some working python code I made into java(as a learning/testing exercise to learn a bit of the differences) but I'm getting different results between the two.
My program takes a list of data and generates another list based on it(basically sees if a value can be broken down by a sum). Python correctly gives 2,578 results while Java only gives 12. I tried to find the same commands in java and thought I did but can't seem to figure out why the results differ(the difference between the two I have experienced problems with multi threading and syncing of variables, wasn't sure if Java was doing anything behind the scenes so I had a while loop to keep running until the results stabilize, but it didn't help). Any suggestions would be helpful.
Here's the offending code(java at the top, python and pseudo code commented out in the bottom as reference):
for (int c = 0; c <= max_value; c++){
String temp_result = (s - c * data.get(i) + "," + i);
if( results.contains( temp_result ) ){
String result_to_add = (s + "," + i+1);
if( results.contains( result_to_add ) ){
System.out.println("contains result already");
} else {
results.add(result_to_add);
} print len(T)
#Here's the basic pseudo code(I added a few control variables but here's a high level view):
for i = 1 to k
for z = 0 to sum:
for c = 1 to z / x_i:
if T[z - c * x_i][i - 1] is true:
set T[z][i] to true
*/
In java s + "," + i+1 is a String concatenation : "10" + "," + 4 + 1 will return 10,41.
Use String result_to_add = s + "," + (i+1); instead.
I see you've solved it just now, but since I've written it already, here's my version:
This uses the trick of using a Point as a substitute for a 2-element Python list/tuple of int, which (coincidentally) bypasses your String concatenation issue.
public class Sums
{
public static void main(String[] args)
{
List T = new ArrayList();
T.add(new Point(0, 0));
int target_sum = 100;
int[] data = new int[] { 10, -2, 5, 50, 20, 25, 40 };
float max_percent = 1;
int R = (int) (target_sum * max_percent * data.length);
for (int i = 0; i < data.length; i++)
{
for (int s = -R; s < R + 1; s++)
{
int max_value = (int) Math.abs((target_sum * max_percent)
/ data[i]);
for (int c = 0; c < max_value + 1; c++)
{
if (T.contains(new Point(s - c * data[i], i)))
{
Point p = new Point(s, i + 1);
if (!T.contains(p))
{
T.add(p);
}
}
}
}
}
System.out.println(T.size());
}
}