Can't find main class in Java? [duplicate] - java

This question already has answers here:
Error "main class not found"
(3 answers)
Closed 8 years ago.
For some reason that I haven't been able to figure out, the program I've been working on for a while now isn't running. This is the error message I've been getting:
All I did between the time it was working and now was add another class, but even after deleting it the error message is still here. Netbeans has also been unhelpful, there aren't any errors marked in red in the code. I'm still a beginner to Java, so I don't know how much is needed to find the error, so here is all of the code:
public class ChooseYourOwn {
static class Character {
private static int str;
public Character() {
int str = 0;
int spd = 0;
int agl = 0;
int def = 0;
int mag = 0;
int wil = 0;
int mp = 0;
int hp = 0;
}
private Character(String name) {
}
}
/**
*
* #param args
* #return
*/
public static int main(String[] args) {
//set up character
System.out.println("Choose a class:");
String [] genusOptions;
genusOptions = new String[] {"\n1-Warrior\n2-Mage\n3-Thief"};
System.out.println(Arrays.toString(genusOptions));
Scanner input1 = new Scanner(System.in);
String genus;
genus = input1.nextLine();
System.out.println("Your character's stats are:");
switch (genus) {
case "1":
{
String[] array = new String[] {"\nStrength-15\nSpeed-5\nAgility-5\nDefense-10\nMagicDamage-5\nMagicDefense-0\nMagicPoints-5\nHitPoints-15\n"};
System.out.println(Arrays.toString(array));
int str = 5;
int spd = 2;
int agl = 2;
int def = 5;
int mag = 0;
int wil = 0;
int mp = 0;
int hp = 10;
break;
}
case "2":
{
String[] array = new String[] {"\nStrength-5\nSpeed-5\nAgility-5\nDefense-0\nMagicDamage-15\nMagicDefense-10\nMagicPoints-15\nHitPoints-5\n"};
System.out.println(Arrays.toString(array));
int str = 5;
int spd = 5;
int agl = 5;
int def = 0;
int mag = 10;
int wil = 10;
int mp = 15;
int hp = 5;
break;
}
case "3":
{
String[] array = new String[] {"\nStrength-10\nSpeed-15\nAgility-15\nDefense-10\nMagicDamage-10\nMagicDefense-5\nMagicPoints-10\nHitPoints-10\n"};
System.out.println(Arrays.toString(array));
int str = 10;
int spd = 15;
int agl = 15;
int def = 10;
int mag = 10;
int wil = 5;
int mp = 10;
int hp = 10;
break;
}
}
String[] array = new String[] {"\n1-Move\n2-Rest\n3-Attack\n4-Run\n5-Activate lever/button/chest\n6-Inventory\n7-Skills"};
System.out.println("Choose a number to continue");
System.out.println(Arrays.toString(array));
Scanner input2;
input2 = new Scanner(System.in);
String action;
action = input2.nextLine();
switch (action) {
case "1":
{
System.out.println("");
//not done yet
break;
}
case "2":
{
System.out.println("");
//Rest, restores some health
break;
}
case "3":
{
System.out.println("");
int max = 100;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
int damage = 0;
if (10 > randomNum) {
damage = (Character.str/100) * 10;
} else if (20 > randomNum) {
damage = (Character.str/100) * 20;
} else if (30 > randomNum) {
damage = (Character.str/100) * 30;
} else if (40 > randomNum) {
damage = (Character.str/100) * 40;
} else if (50 > randomNum) {
damage = (Character.str/100) * 50;
} else if (60 > randomNum) {
damage = (Character.str/100) * 60;
} else if (70 > randomNum) {
damage = (Character.str/100) * 70;
} else if (80 > randomNum) {
damage = (Character.str/100) * 80;
} else if (90 > randomNum) {
damage = (Character.str/100) * 90;
} else if (100 > randomNum) {
damage = Character.str;
}
System.out.println( damage );
break;
}
case "4":
{
System.out.println("");
//not done yet
break;
}
case "5":
{
System.out.println("");
//not done yet
break;
}
case "6":
{
System.out.println("");
//not done yet
break;
}
case "7":
{
System.out.println("");
//not done yet
}
}
return (0);
}
}
There have been similar questions asked here before, but none of them helped and others were very unclear. A good and coherent answer would be much appreciated, thanks.

In Java, the main method signature is public static void main(String[] args), however in your code you are using public static int main(String[] args).

Java main methods are declared like this:
public static void main(String[] args) {
...
}
More information can be found at Can a main method in Java return something?

You can't change the return type of main. This,
public static int main(String[] args)
must be one of (per this worthwhile Wikipedia article on Entry point)
public static void main(String[] args)
public static void main(String... args)
public static void main(String args[])
All of which are void, if you need to set a UNIX style return type, you can use System.exit(int); to quote the Javadoc that
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Related

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

Stuck on replacing array

I've used to site for many commands I had trouble using and it was very helpful. I thought you guys might be able to help me out and help me understand what i'm doing wrong here. The "Rabbit"/"R" is moving as I wanted, however the old position is not resetting its old value from the copied array. Logic for winning and losing aren't debugged, yet so ignore that.
EDIT*
I can't shorten the code due to the relations between the array has with the program. The precise description for the error is when the "Rabbit"/"R" moves from (Using representative values) GridCompOne[5][5] to GridCompOne[4][5] going "up" on the "grid" I have a second array called GridCompTwo which is a copied version of the first grid when the random values were generated. What is supposed to happen is the Rabbit's value, which = 4 is supposed to replace GridCompOne[4][5] to = 4 and the old position GridCompOne[5][5] is supposed to be replaced with GridCompTwo[5][5] old value being 3 which is supposed to represent the ground value I have assigned. But the replacing of the value doesn't seem to work.
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (0);
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2);
{
game.Ready();
grid.RandomGridGenerator();
spawner.RabbitWolfSpawner();
movement.Copy();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
The root cause for the problem is System.arraycopy. As of my understanding it is copying reference instead of values (may be i am wrong).
i changed to manual copy then it is working fine up to the logic of replacing array. Please check below modified code with my comments
import java.util.Random;
import java.util.Scanner;
public class SurvivalGameVersionTwo
{
private int Repeat;
public int WinLose = (1);
private int Turn = (1);
public static void main(String[] args)
{
String User;
int Repeat = (3);//changed: to enter into while loop Repeat should be more than 2
//Creating Objects
SurvivalGameVersionTwo game = new SurvivalGameVersionTwo();
Score score = new Score();
Grid grid = new Grid();
Spawner spawner = new Spawner();
Display display = new Display();
User user = new User();
Time time = new Time();
Logic logic = new Logic();
Movement movement = new Movement();
//Calling object's class methods
Intro();
User = GetUser();
user.setName(User);
while (Repeat > 2)//changed: removed ;
{
game.Ready();
grid.RandomGridGenerator();
movement.Copy();//changed:First copy then change GridCompOne array
spawner.RabbitWolfSpawner();
while (game.WinLose <= 2)
{
display.UserGrid();
game.Turn = Turns(game.Turn);
movement.Movement();
game.WinLose = logic.WinLose(game.Turn);
time.Delay();
}
display.UserGrid();
Repeat = Repeat();
game.WinLose = (1);
}
}
public static void Intro()
{
System.out.printf("Welcome to the Rabbit Survival Game!\n");
System.out.println("Rules to win: Rabbit must cross the bridge.");
System.out.println("Rules to lose: Rabbir drowns in the water, \n"+
"eaten by the wolf, or starve to death in 30 turns.");
System.out.println("------------------------------------------");
}
public static String GetUser()
{
Scanner Input = new Scanner (System.in);
String Name;
System.out.println("Please type in your name please.");
Name = Input.next();
return Name;
}
public static void Ready()
{
Scanner Input = new Scanner (System.in);
String Ready;
String Yes = ("Yes");
String No = ("No");
System.out.println("Are you ready to play?");
System.out.println("Type in 'Yes', or 'No' to continue.");
Ready = Input.next();
if (Ready.equals(Yes) == true)
{
System.out.println("Lets begin!!!");
}
else if (Ready.equals(No) == true)
{
System.out.println("Goodbye, and hope you come back to play again.");
System.exit(0);
}
else
{
System.out.println("There was an error!!! Restart the program to try again.");
System.exit(0);
}
}
public static int Turns(int turns)
{
int Turns;
System.out.printf("Turn %d.",turns);
Turns = (turns + 1);
return Turns;
}
public static int Repeat()
{
Scanner Input = new Scanner (System.in);
int repeat;
System.out.println("Do you wish to play again?");
repeat = Input.nextInt();
return repeat;
}
}
class User
{
private String Name;
public void UserInfo(String name)
{
this.Name=name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
class Score
{
public static int Total = 0;
public static int Win = 0;
public static int Lose = 0;
public static double Ratio = 0;
}
class Grid {
public static int[][] GridCompOne = new int[10][10];
public static int[] Rabbit = new int[2];
public static int[] Wolf = new int[2];
public static void RandomGridGenerator() {
Random r = new Random();
int i = 1;
int j = 1;
int k = 0;
int Low = 1;
int High = 3;
int Random;
//parameters for bridge and water spawning
while (k <= 9) {
Random = r.nextInt(High - Low) + Low;
GridCompOne[0][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][0] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[9][k] = Random;
Random = r.nextInt(High - Low) + Low;
GridCompOne[k][9] = Random;
k++;
}
while (i <= 8) {
while (j <= 8) {
GridCompOne[i][j] = 3;
j++;
}
j = 1;
i++;
}
}
}
class Spawner extends Grid
{
public static void RabbitWolfSpawner()
{
Random r = new Random();
int Low = 1;
int High = 8;
int XAxis;
int YAxis;
int Random;
//Rabbit
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 4;
Rabbit[0] = XAxis;
Rabbit[1] = YAxis;
//Wolf
Random = r.nextInt(High - Low) + Low;
XAxis = Random;
Random = r.nextInt(High - Low) + Low;
YAxis = Random;
GridCompOne[XAxis][YAxis] = 5;
Wolf[0] = XAxis;
Wolf[1] = YAxis;
}
}
class Movement extends Grid
{
private static int[][] GridCompTwo = new int[10][10];
public static void Copy()
{
//System.arraycopy(GridCompOne, 0, GridCompTwo, 0, GridCompOne.length);
//changed
//As of my understanding System.arraycopy is not coping values , it is copying references
for(int i=0;i<GridCompOne.length;i++){
for(int j=0;j<GridCompOne[i].length;j++){
GridCompTwo[i][j]=GridCompOne[i][j];
}
}
}
//Rabbit and Wolf Movement
public static void Movement()
{
int High = 4;
int Low = 1;
Random R = new Random();
int Random = R.nextInt(High - Low) + Low;
//Rabbit
switch (Random)
{
case 1:
{
//Up
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] - 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] - 1);
break;
}
case 2:
{
//Down
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0] + 1][Rabbit[1]] = 4;
Rabbit[0] = (Rabbit[0] + 1);
break;
}
case 3:
{
//Left
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] - 1] = 4;
Rabbit[1] = (Rabbit[1] - 1);
break;
}
case 4:
{
//Right
GridCompOne[Rabbit[0]][Rabbit[1]] = GridCompTwo[Rabbit[0]][Rabbit[1]];
GridCompOne[Rabbit[0]][Rabbit[1] + 1] = 4;
Rabbit[1] = (Rabbit[1] + 1);
break;
}
default:
{
System.out.println("There was an error!!!");
System.exit(0);
}
}
Random = R.nextInt(High - Low) + Low;
//Wolf
switch (Random)
{
case 1: {
//Up
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] - 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] - 1);
break;
}
case 2: {
//Down
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0] + 1][Wolf[1]] = 5;
Wolf[0] = (Wolf[0] + 1);
break;
}
case 3: {
//Left
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] - 1] = 5;
Wolf[1] = (Wolf[1] - 1);
break;
}
case 4: {
//Right
GridCompOne[Wolf[0]][Wolf[1]] = GridCompTwo[Wolf[0]][Wolf[1]];
GridCompOne[Wolf[0]][Wolf[1] + 1] = 5;
Wolf[1] = (Wolf[1] + 1);
break;
}
default: {
System.out.println("There was an error!!!");
System.exit(0);
}
}
}
}
class Display extends Movement
{
private static char[][] GridUser = new char[10][10];
public static void UserGrid()
{
int i = 0;
int j = 0;
char Letter = ' ';
System.out.println("---------------------");
while (i <= 9)
{
while (j <= 9)
{
System.out.print("|");
switch (GridCompOne[i][j])
{
case 1:
{
//Water
Letter = '~';
break;
}
case 2:
{
//Bridge
Letter = '=';
break;
}
case 3:
{
//Ground
Letter = ',';
break;
}
case 4:
{
//Rabbit
Letter = 'R';
break;
}
case 5:
{
//Wolf
Letter = 'W';
break;
}
default:
{
//Error!!!
System.out.println("There was an error in the program!!!");
System.exit(0);
}
}
GridUser[i][j] = Letter;
System.out.print(GridUser[i][j]);
j++;
}
System.out.print("|");
System.out.println();
System.out.println("---------------------");
j = 0;
i++;
}
}
}
class Logic extends Grid
{
public static int WinLose(int counter)
{
int winlose = (0);
if(GridCompOne[Rabbit[0]][Rabbit[1]]==1)
{
System.out.println("The Rabbit has drowned!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==2)
{
System.out.println("The Rabbit has Escaped!");
System.out.println("Game over!");
Score.Win = Score.Win + 1;
winlose = 3;
}
else if(GridCompOne[Rabbit[0]][Rabbit[1]]==5)
{
System.out.println("The Rabbit has been Eaten by the Wolf!");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else if(counter>30)
{
System.out.println("The Rabbit has starved to death");
System.out.println("Game over!");
Score.Lose = Score.Lose + 1;
winlose = 3;
}
else
{
System.out.println(" (Next Turn in a couple seconds)");
}
return winlose;
}
}
class Time
{
public static void Delay()
{
try
{
long Seconds = (2000);
Thread.sleep(Seconds);
}
catch (InterruptedException e)
{
System.out.println("...");
}
}
}
Thanks

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

Roman Numeral to Number Conversion [duplicate]

This question already has answers here:
Converting Roman Numerals To Decimal
(30 answers)
Closed 9 years ago.
Trying to write program to read in a string of characters that represent a Roman numeral (from user input) and then convert it to Arabic form (an integer). For instance, I = 1, V = 5, X = 10 etc.
Basically, the constructor that takes a parameter of type String must interpret the string (from user input) as a Roman numeral and convert it to the corresponding int value.
Is there an easier way to solve this besides the below in progress (which isn't compiling as yet):
import java.util.Scanner;
public class RomInt {
String roman;
int val;
void assign(String k)
{
roman=k;
}
private class Literal
{
public char literal;
public int value;
public Literal(char literal, int value)
{
this.literal = literal;
this.value = value;
}
}
private final Literal[] ROMAN_LITERALS = new Literal[]
{
new Literal('I', 1),
new Literal('V', 5),
new Literal('X', 10),
new Literal('L', 50),
new Literal('C', 100),
new Literal('D', 500),
new Literal('M', 1000)
};
public int getVal(String s) {
int holdValue=0;
for (int j = 0; j < ROMAN_LITERALS.length; j++)
{
if (s.charAt(0)==ROMAN_LITERALS[j].literal)
{
holdValue=ROMAN_LITERALS[j].value;
break;
} //if()
}//for()
return holdValue;
} //getVal()
public int count()
{
int count=0;
int countA=0;
int countB=0;
int lastPosition = 0;
for(int i = 0 ; i < roman.length(); i++)
{
String s1 = roman.substring(i,i+1);
int a=getVal(s1);
countA+=a;
}
for(int j=1;j<roman.length();j++)
{
String s2= roman.substring(j,j+1);
String s3= roman.substring(j-1,j);
int b=getVal(s2);
int c=getVal(s3);
if(b>c)
{
countB+=c;
}
}
count=countA-(2*countB);
return count;
}
void disp()
{
int result=count();
System.out.println("Integer equivalent of "+roman+" = " +result);
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt();
}
}
Roman numerals/Decode Example:
class Roman {
private static int decodeSingle(char letter) {
switch (letter) {
case 'M':
return 1000;
case 'D':
return 500;
case 'C':
return 100;
case 'L':
return 50;
case 'X':
return 10;
case 'V':
return 5;
case 'I':
return 1;
default:
return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for (int i = 0; i < uRoman.length() - 1; i++) {//loop over all but the last character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))) {
result -= decodeSingle(uRoman.charAt(i));
} else {
result += decodeSingle(uRoman.charAt(i));
}
}
result += decodeSingle(uRoman.charAt(uRoman.length() - 1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
}
Use enum, for easy and simple solution. At first define the decimal equivalent weight at roman.
enum Roman{
i(1),iv(4),v(5), ix(9), x(10);
int weight;
private Roman(int weight) {
this.weight = weight;
}
};
This is the method to convert decimal to roman String.
static String decToRoman(int dec){
String roman="";
Roman[] values=Roman.values();
for (int i = values.length-1; i>=0; i--) {
while(dec>=values[i].weight){
roman+=values[i];
dec=dec-values[i].weight;
}
}
return roman;
}
You can try using a Hashmap to store the roman numerals and equivalent arabic numerals.
HashMap test = new HashMap();
test.add("I",1);
test.add("V",5);
test.add("X",10);
test.add("L",50);
test.add("C",100);
test.add("D",500);
test.add("M",1000);
//This would insert all the roman numerals as keys and their respective arabic numbers as
values.
To retrieve respective arabic numeral one the input of the user, you can use following peice of code:
Scanner sc = new Scanner(System.in);
System.out.println(one.get(sc.next().toUpperCase()));
//This would print the respective value of the selected key.This occurs in O(1) time.
Secondly,
If you only have these set of roman numerals, then you can go for simple switch case statement.
switch(sc.next().toUpperCase())
{
case 'I' :
System.out.println("1");
break;
case 'V'
System.out.println("5");
break;
.
.
.
& so on
}
Hope this helps.
How about this:
public static int convertFromRoman(String roman) {
Map<String, Integer> v = new HashMap<String, Integer>();
v.put("IV", 4);
v.put("IX", 9);
v.put("XL", 40);
v.put("CD", 400);
v.put("CM", 900);
v.put("C", 100);
v.put("M", 1000);
v.put("I", 1);
v.put("V", 5);
v.put("X", 10);
v.put("L", 50);
v.put("D", 500);
int result = 0;
for (String s : v.keySet()) {
result += countOccurrences(roman, s) * v.get(s);
roman = roman.replaceAll(s, "");
}
return result;
}
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Not sure I've got all possible combinations as I'm not an expert in roman numbers. Just make sure that the once where you substract come first in the map.
Your compilation issue can be resolved with below code. But surely its not optimized one:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt temp = new RomInt();
temp.getVal(s);
temp.assign(s);
temp.disp();
}

Categories

Resources