Java program takes input but does not output - java

When I try to run the program it asks me for my input and then just says "running" without any output until I close it. I do not see any issues with the code, and I have run this exact program before on a different computer (my home computer is far superior in processing power to the PC it ran on) is this a Netbeans bug?
int ticket [] = new int [6];
for (int i = 0; i < 6; i++)
{
ticket [i] = Integer.parseInt(JOptionPane.showInputDialog("Input a number:"));
}
int balls[] = new int [7];
for (int i = 0; i < balls.length; i++)
{
boolean keepLooking = true;
int b = (int)(Math.random()*6 + 1);
while(keepLooking)
{
keepLooking = false;
for (int j = 0; j < balls.length; j++)
{
if (balls [j] == b)
{
keepLooking = true;
}
}
}
balls [i] = b;
}
int bonus = balls[6];
int matching = 0;
boolean bonusMatch = false;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
if (ticket[i] == balls[j])
{
matching = matching +1;
}
}
if (ticket[i] == balls[6])
{
bonusMatch = true;
}
}
System.out.println("The winning balls are: ");
for (int i = 0; i < 6; i++)
{
System.out.print(" " +balls[i]);
}
System.out.println(" And the bonus ball is " +balls[6]);
int Payout = 0;
if (matching == 3)
{
System.out.println("Your payout was: R57");
}
else if (matching == 4)
{
System.out.println("Your payout was: R1033");
}
else if (matching == 5)
{
if (bonusMatch = true)
{
System.out.println("Your payout was: R2300000");
}
else
{
System.out.println("Your payout was: R55491");
}
}
else if (matching == 6)
{
System.out.println("Your payout was: R14000000");
}
}

int b = (int)(Math.random()*6 + 1);
if b is twice the same (it's random, it can happen and will happen), you have an infinite loop (keepLooking = true since you found b in your table, and you iterate without changing anything).
whatever you are trying to achieve (honestly your code made no sense, create methods with meaningful names, avoid intricate loops, brief refactor), bug's on you, not Netbeans.

please use "if" loop instead of "while" loop you will get a output like what u want!!i.e.,
while(keepLooking) instead use if(keepLooking)

Related

How to check if a number multiplies to something but adds to something

So I've been trying to make some sort of a calculator tool. One of the function is to check if a factor of a number multiplies to something but at the same time adds to something else. This is helpful for factoring a trinomial. I found the factors but I don't know how to proceed. This is what I have so far
public static void MA() {
int sum = 0;
int product = 0;
ArrayList<Integer> Factors = new ArrayList<Integer>();
System.out.println("Enter the sum of the number");
sum = sc.nextInt();
System.out.println("Enter the number it should multiply to");
product = sc.nextInt();
if(product < 0){
for(int i = product; i <= Math.abs(product); ++i) {
// skips the iteration for i = 0
if(i == 0) {
continue;
}
else {
if (product % i == 0) {
Factors.add(i);
}
}
}
}
else{
for (int i = 1; i <= product; ++i) {
// if number is divided by i
// i is the factor
if (product % i == 0) {
Factors.add(i);
}
}
}
System.out.println(Factors);
}
Keep in mind the architecture of my program is a main class that calls on all other functions.
EXAMPLE: X^2 + 9x + 20 = (x+5)(x+4)
4*5 = 20
4+5 = 9
Your problem can be succinctly expressed as follows:
Given a List<Integer>, find 2 of its elements that sum to a given number.
A simple solution to which is:
List<Integer> factors = new ArrayList<>(); // populated elsewhere
int sum = ?; // whatever
Integer a = null;
Integer b = null;
outer:
for (int i = 0; i < factors.size() - 1; i++) {
for (int j = i + 1; j < factors.size(); j++) {
if (factors.get(i) + factors.get(j) == sum) {
a = factors.get(i);
b = factors.get(j);
break outer;
}
}
}
If a and b are not null, a pair that summed to sum was found.

java - Input 2 integer arrays and print alternating elements

Conditions:
both arrays must be in order or error message
the first array must be as long as or longer than the second or error message
if the first is longer than the second it must continue to print the first
Example: given setF[] = 1,2,3,4,8 and setS[] =5,6,7 it prints 1, 5, 2, 6, 3, 7, 4, 8
The Problem With My Code: It will print and alternate fine, but will not continue to print the first areay if it's longer.
full code (I apologize for slightly messy formatting. The website screwed it up a little bit):
package mergearrays;
import java.io.*;
import java.lang.*;
import java.util.*;
public class MergeArrays {
public static void main(String[] args) {
//variables
boolean done = false;
boolean error = false;
int inpval = 0;
int i = 0; //will be setF.length
int j = 0; //will be setS.length
//arrays
int [] vals = new int[20000];
//ask user
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit");
//input array
Scanner scan = new Scanner(System.in);
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[i] = inpval;
i++;
}
else {
done = true;
}
}
done = false;
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit");
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[j+i+1] = inpval;
j++;
}
else {
done = true;
}
}
//new arrays
int [] setF = new int[10000];
int [] setS = new int[10000];
//copy vals into setF and setS
System.arraycopy(vals, 0, setF, 0, i);
System.arraycopy(vals, i+1, setS, 0, i+j+1);
//check for order
for (int p = 0; p < i - 1; p++) {
if (setF[p] > setF[p+1]) {
error = true;
break;
}
}
for (int b = 0; b < j - 1; b++) {
if (setS[b] > setS[b+1]) {
error = true;
break;
}
}
//print first array
System.out.print("\n First Array: ");
for(int q = 0; q < i; q++) {
System.out.print(setF[q] + " ");
}
//print second array
System.out.print("\n Second Array: ");
for(int m = 0; m < j; m++) {
System.out.print(setS[m] + " ");
}
//print the final set
if(i >= j && error == false){
System.out.print("\n Merged Array: ");
for(int n = 0; n <= i+j; n++) {
if(setF[n] != 0 && setS[n] !=0) {
if(n <= j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
}
else if(n > j && n <= i){
System.out.print(setF[n] + " ");
}
}
}
}
//error message
else {
System.out.print("\n ERROR: Array not in correct order");
}
}
}
the reason it didn't continue to print for you if the first array is longer lies in this line of code:
if (setF[n] != 0 && setS[n] != 0) {
You continued to print only if both of the array at the same position were zero. You should check here 'OR' not 'AND'. In addition, after changing that condition to 'OR', the ifs inside need to be changed as well, because the indexes are not correct. As follows:
System.out.print("\n Merged Array: ");
for (int n = 0; n <= i + j; n++) {
if (setF[n] != 0 || setS[n] != 0) {
if (n < j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
} else if (n < i) {
System.out.print(setF[n] + " ");
}
}
}
I would have solved it in a different way, and I can guide you to if you need some help. Anyways, Hope this helps...

Issue with Game of life code method? (User interface is complete but actual GOL methods aren't generating what they should)

I've been working on a Game of Life assignment and am nearing the stage of completion, but am struggling to figure out what I've messed up on such that the GOL rules (and Fredkin rules that the assignment requires us to implement as well) are not generating the proper result.
As I have little experience working with graphics I decided to output everything in the interactions window (using Dr.Java). (It's used to set up menu options like the scale, coordinates (you manually enter), generations, and output the final generation of whichever rule you choose to run (GOL or Fredkin).
The program nextGeneration takes a Boolean array map from the main method (where people input coordinates), and should change it to correspond to the next generation of the Game of Life. This happens by creating an entirely new 2D array, map2, which gets values loaded into it based on the number of neighbors which are turned on for each point. At the end of the program, map gets loaded into map2.(Note: this isn't original, this is required by the assignment)
The program living merely checks if a point in the map array is on or off. countNeighbors takes the 8 neighbors of a particular square, passes them each through the living method, and returns the number of neighbors which are currently on. Since countNeighbors sometimes demands either a negative number, or a number greater than the scale of the map, we implemented conditions in living to create that wraparound universe.
I think the problem(s) most likely arise in nextGeneration. I am somewhat tense about using the operand "or" (written as || ), and I think this may be where I screwed up. If you could just look through the code, and see if what I have said is true is written as true, that would be absolutely wonderful.
Below is the code for the program. It also utilizes a Keyboard.class file which I'm happy to post (however one would do that) if that helps (it's required to compile).
public class GameOfLife {
public static void main(String[] args) {
int r = 0; //rules set. Either 0 or 1, 0 for life game, 1 for Fredkin game
int i = 0; // looping variable
int j = 0; // looping variable
int b = 0; // used to read integer inputs from keyboard
int x = 0; // used during the stage where the player manually changes the board. Represents x coordinate.
int y = 0; // used during the stage where the player manually changes the board. Represents x coordinate.
int gen = 0; //number of generations to be skipped before printing out new map
int scale = 0;
boolean[][] map = new boolean[0][0];
System.out.println("Start game? y/n");
String a = Keyboard.readString();
if (a.equals("n")) {
return;
} else {
System.out.println("Do you wish to know the rules? y/n");
a = Keyboard.readString();
if (a.equals("y")) {
System.out.println("Each coordinate in the printed graph is represented by a 0 or a .");
System.out.println("0 represents a live cell, . represents a dead one.");
System.out.println("Each cell has 8 neighboring cells.");
System.out.println("There are two ways in which the game can be played.");
System.out.println("In the Life model, if a cell has 3 neighbors, if dead, it turns on.");
System.out.println("If it has 2 neighbors, it keeps its current condition.");
System.out.println("Else, it dies. Brutal.");
System.out.println("In the Fredkin Model, only non-diagnol neighbors count.");
System.out.println("If a cell has 1 or 3 neighbors, it is alive.");
System.out.println("If it has 0, 2 or 4, it dies. WAY more Brutal.");
}
System.out.println("Do you want to play by Fredkin or Life Rules? 0 for life, 1 for Fredkin");
while (i == 0) {
b = Keyboard.readInt();
if (b == 1) {
r = 1;
i = 1;
}
if (b == 0) {
r = 0;
i = 1;
}
}
while (j == 0) {
System.out.println("What scale would you like to use? Please enter an integer larger than 4");
b = Keyboard.readInt();
if (b >= 5) {
map = new boolean[b][b];
scale = b;
j = 1;
} else {
System.out.println("Come on, buddy, read the rules");
}
}
j = 0;
while (j == 0) {
System.out.println("Do you want to enter coordinates? y to continue entering coordinates, n to go to next option");
a = Keyboard.readString();
if (a.equals("y")) {
i = 0;
while (i == 0) {
System.out.println("Please enter a value for an X coordinate from 0 to " + (scale - 1));
b = Keyboard.readInt();
if (b >= 0) {
if (b < scale) {
i = 1;
x = b;
}
}
}
i = 0;
while (i == 0) {
System.out.println("Please enter a value for a Y coordinate from 0 to " + (scale - 1));
b = Keyboard.readInt();
if (b >= 0) {
if (b < scale) {
i = 1;
y = b;
}
}
}
map[y][x] = true;
printgame(map);
} else {
if (a.equals("n")) {
j = 1;
}
}
}
i = 0;
while (i == 0) {
System.out.println("How many generations would you like to skip ahead? Please enter a value greater than 0");
b = Keyboard.readInt();
if (b > 0) {
gen = b;
i = 1;
}
}
i = 0;
if (r == 0) {
for (i = 0; i <= gen; i++) {
nextGeneration(map);
}
printgame(map);
} else {
if (r == 1) {
for (i = 0; i <= gen; i++) {
FredGen(map);
}
printgame(map);
}
}
}
}
public static void printgame(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int i = 0;
int j = 0;
char c;
String Printer = "";
for (j = 0; j < y; j++) {
for (i = 0; i < x; i++) {
if (map[j][i]) {
c = '0';
} else {
c = '.';
}
Printer = (Printer + " " + c);
}
System.out.println(Printer);
Printer = new String("");
}
}
private static void nextGeneration(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int[][] neighborCount = new int[y][x];
boolean[][] map2 = new boolean[y][x];
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
neighborCount[j][i] = countNeighbors(j, i, map);
//this makes a new generation array
for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) {
if (map[j][i] = true) { //assumes initial value of array is true (AKA "ALIVE")
if (neighborCount[j][i] == 3) { //check if alive AND meeting condition for life
map2[j][i] = true; //sets character array coordinate to ALIVE: "0"
} else if ((neighborCount[j][i] <= 2) || (neighborCount[j][i] > 3)) { //check if dead from isolation or overcrowding
map2[j][i] = false; //sets character array coordinate to DEAD: "."
}
}
}
}
map = map2;
}
private static int countNeighbors(int j, int i, boolean[][] map) { //counts all 8 elements living/dea of 3x3 space surrounding and including living/dead central coordinate)
return living(j - 1, j - 1, map) + living(j - 1, i, map) +
living(j - 1, i + 1, map) + living(j, i - 1, map) + living(j, i + 1, map) +
living(j + 1, i - 1, map) + living(j + 1, i, map) + living(j + 1, i + 1, map);
}
private static int living(int j, int i, boolean[][] map) {
int x = map[0].length - 1;
if (i < 0) {
i = i + x;
} else {
i = i % x;
}
if (j < 0) {
j = j + x;
} else {
j = j % x;
}
if (map[j][i] == true) {
return 1;
} else {
return 0;
}
}
private static void FredGen(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int[][] neighborCount = new int[y][x];
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
neighborCount[j][i] = Freddysdeady(j, i, map);
//this makes a new generation array
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
if (map[j][i] = true) { //assumes initial value of array is true (AKA "ALIVE")
if ((neighborCount[j][i] < 1) || (neighborCount[j][i] == 2) || (neighborCount[j][i] > 3)) { //check if dead from isolation or overcrowding
map[j][i] = false; //sets chracter array coordinate to DEAD: "."
} else if ((neighborCount[j][i] == 1) || (neighborCount[j][i] == 3)) { //check if alive AND meeting condition for life
map[j][i] = true; //sets character array coordinate to ALIVE: "0"
}
}
}
private static int Freddysdeady(int j, int i, boolean[][] map) {
return living(j - 1, i, map) + living(j, i - 1, map) + living(j, i + 1, map) + living(j + 1, i, map);
}
}
There might be other problems, here are a few that I could spot by eye:
In the nextGeneration method, you handle cases where a cell should stay alive or die, but you do not have anything for when cells should be born. You should have something like this:
if(map[x][y]) {
//should this cell stay alive? if yes = live, else die
} else {
//should a cell be born in this slot? if yes = born, else nothing
}
This is a minor issue, still in nextGeneration, in if(count==3)live; else if(count <=2 || count > 3) die; is redundant, you only need if(count == 3) live; else die;
let us know, if you still have problems

Guessing the number that the user has thought with java (arrays)

I'm kind of new at programming and our teacher asked us to make a programme that can guess the number the user has thought using arrays. I did this:
import java.util.Scanner;
public class Exercise11 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Think a number between 1 and 100");
int array[] = new int[100];
for (int x = 0; x < 100; x++) {
array[x] = (int) ((Math.random() * 100) + 1);
}
//This allow us to fill the array with random numbers, without caring if they are repeated or not.
for (int i = 0; i < 100; i++) {
for (int j = 0; i < 100; j++) {
while (true) {
if (i != j && array[i] == array[j]) {
array[j] = (int) ((Math.random() * 100) + 1);
} else
break;
}
//If a number is repeated, this will swap that number with another number.
}
}
//Now we have filled the array. We ask the user:
for (int y = 0; y < 100; y++) {
System.out.println("¿Is it your number " + array[y] + "?");
String respuesta = entrada.next();
switch (respuesta) {
case "Yes":
System.out.println("I knew it! I only needed " + y + " trys!");
break;
case "No":
break;
}
}
}
}
But it is still throwing errors when I execute it, like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Ejercicio11.main(Ejercicio11.java:25).
I have tried to debug it but I'm still learning how to do it and I cannot find the mistake. Can someone help me identify where the error is and how can I fix it? Thanks a lot!
The condition of your inner for loop should be
for (int j = 0; j < 100; j++){
(The condition is j < 100, not i < 100)

My java program is showing runtime error while submitting it on uva.onlinejudge.org

I am trying to solve a uva problem "Greedy Gift Givers" (problem number 119, Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=55 ). I am using java to solve that problem and my code works fine while running it on my computer, but the problem is when I submit it to uva online judge it shows me RUNTIME ERROR. I did not get where the problem is. I also have less idea about RUNTIME ERROR. My code is given below
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = 0;
String name[];
int cost[];
while (inp.hasNextLine()) {
n = inp.nextInt();
name = new String[n];
cost = new int[n];
for (int i = 0; i < n; i++) {
name[i] = inp.next();
}
for (int p = 0; p < n; p++) {
String temp_name = inp.next();
for (int i = 0; i < n; i++) {
if (temp_name.equals(name[i])) {
int gift = inp.nextInt(), num = inp.nextInt();
if (num != 0 && gift >= 0) {
cost[i] -= (int) (gift / num) * (int) num;
}
for (int k = 0; k < num; k++) {
String temp_name_2 = inp.next();
for (int j = 0; j < n; j++) {
if (temp_name_2.equals(name[j])) {
if (num != 0 && gift >= 0) {
cost[j] += gift / num;
}
break;
}
}
}
break;
}
}
}
for (int i = 0; i < n; i++) {
System.out.println(name[i] + " " + cost[i]);
}
}
}
}
I think the error is that you use System.in while the online judge gives a file to the input of your program. The last string og the input section:
The input consists of one or more groups and is terminated by end-of-file.

Categories

Resources