Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
When i try to compile this code i get this error:
dn09.java:38: error: illegal start of expression
public Tip[] preberi (Scanner sc) {
^ dn09.java:38: error: ';' expected
public Tip[] preberi (Scanner sc) {
^ dn09.java:38: error: ';' expected
public Tip[] preberi (Scanner sc) {
^ 3 errors
[Napaka | process.javac]: Object reference not set to an instance of an object.
This is the line of code in the question:
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
tipi[i] = new Prim(sc.nextInt());
break;
case "arr":
tipi[i] = new Arr(sc.nextInt(), sc.nextInt());
break;
case "ostruct":
break;
case "pstruct":
break;
}
}
return tipi;
}
I have my Scanner declared up in the main() method, it is imported and everything.
As some of you asked this is my whole code(it isnt in working state at all, as you will also see im a beginner so its preety simple.
public class dn09 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
int d = sc.nextInt();
Tip[] tipi = preberi(sc);
int u = sc.nextInt();
int[] ukazi = new int[u];
for (int i = 0; i < u; i++) {
ukazi[i] = sc.nextInt(); //if you know a better way to store 2 numbers where i could then
//use the numbers separately that would be super helpfull as id
} //need it for 2 switch statements which im currenty trying to
for (int i = 0; i < u; i++) {//fit into 1.
switch(ukazi[i]) {
case 11:
break;
case 12:
break;
case 13:
break;
case 21:
break;
case 22:
break;
case 23:
break;
case 31:
break;
case 32:
break;
case 33:
break;
}
}
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
tipi[i] = new Prim(sc.nextInt());
break;
case "arr":
tipi[i] = new Arr(sc.nextInt(), sc.nextInt());
break;
case "ostruct":
break;
case "pstruct":
break;
}
}
return tipi;
}
}
private static class Prim extends dn09 {
protected int v;
public static Prim (int v) {
this.v = v;
}
}
private static class Arr extends dn09 {
protected int n;
protected int t;
public static Arr (int n, int t) {
this.t = t;
this.n = n;
}
}
}
Your main() method needs a closing } you only close the loop and switch.
You also need to remove the two static from your inner classes constructors (Prim(int) and Arr(int,int)). There is a dangling } at the end, perhaps you want to remove the one which closes it?
If you use an IDE and auto-indent the code, those problems get quickly visible.
public class dn09 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
int d = sc.nextInt();
Tip[] tipi = preberi(sc);
int u = sc.nextInt();
int[] ukazi = new int[u];
for (int i = 0; i < u; i++) {
ukazi[i] = sc.nextInt(); //if you know a better way to store 2 numbers where i could then
//use the numbers separately that would be super helpfull as id
} //need it for 2 switch statements which im currenty trying to
for (int i = 0; i < u; i++) {//fit into 1.
switch(ukazi[i]) {
case 11:
break;
...
}
}
}
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
liki[i] = new Prim(sc.nextInt());
break;
...
}
}
return tipi;
}
private static class Prim extends dn09 {
protected int v;
public Prim (int v) {
this.v = v;
}
}
private static class Arr extends dn09 {
protected int n;
protected int t;
public Arr (int n, int t) {
this.t = t;
this.n = n;
}
}
}
Related
This is the code that is meant to call a class called Couple and yet
it doesn't recognize the class why is this?
public class AgencyInterFace {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int choice, position;
showSelection();
choice = console.nextInt();
while (choice != 9) {
switch (choice) {
case 1:
addCouple();
break;
case 2:
position = console.nextInt();
testCouple(position);
break;
case 3:
position = console.nextInt();
displayCouple(position);
break;
case 9:
break;
default:
System.out.println("Invalid Selection");
} //end switch
showSelection();
choice = console.nextInt();
}
}
public static void showSelection() {
System.out.println("Select and enter");
System.out.println("1 - add a new couple");
System.out.println("2 - test a couple");
System.out.println("3 - display couple");
System.out.println("9 - exit");
}
public static void addCouple() {
Scanner console = new Scanner(System.in);
String herName, hisName;
int herAge, hisAge, ageDiff;
System.out.print("her name: ");
herName = console.nextLine();
System.out.print("her age: ");
herAge = console.nextInt();
System.out.print("his name: ");
hisName = console.nextLine();
System.out.print("his age: ");
hisAge = console.nextInt();
ageDiff = herAge - hisAge;
c.addData(herName, herAge, ageDiff, hisName, hisAge, ageDiff);
}
public static void testCouple(int position) {
System.out.println(c.test(position));
}
public static void displayCouple(int position) {
System.out.println(c.display(position));
}
public static void averageAge(int position) {
System.out.println(c.avgAge());
}
public static void maxDifference(int position) {
System.out.println(c.maxDif(position));
}
public static void averageDifference(int position) {
System.out.println(c.avgDif(position));
}
}//end of class
This code is the class that is meant to be called and that is not
being recognized and is unable to be called.
public class Couple {
final private int MAX = 5;
private Person[] p1, p2;
private int total;
public Couple() {
p1 = new Person[MAX];
p2 = new Person[MAX];
total = 0;
}
private void setData1(Person p, String name, int age, int ageDiff) {
p.setName(name);
p.setAge(age);
}
public String test(int pos) {
if (pos != -1) {
if (p1[pos].getAge() < p2[pos].getAge()) return ("GOOD FOR
"+p2[pos].getName()+" !");
else return ("GOOD
FOR "+p1[pos].getName()+" !");
}
return "error";
}
public void addData(String name1, int age1, int ageDiff1, String
name2, int age2, int ageDiff2) {
p1[total] = new Person();
p2[total] = new Person();
setData1(p1[total], name1, age1, ageDiff1);
setData1(p2[total], name2, age2, ageDiff2);
total++;
}
public String display(int position) {
if (position != -1)
return ("p1: " + p1[position].getName() + "
"+p1[position].getAge()+" / n "+" p2:
"+p2[position].getName()+"
"+p2[position].getAge());
else
return ("error");
}
public String avgAge(int position) {
double avg = 0;
double sum = 0.0;
for (int i = 0; i < position; i++) {
sum += p1[total].getAge();
sum += p2[total].getAge();
}
avg = sum / position;
return ("The average age is: " + avg);
}
public void ageDifference(int position) {
double ageDif = 0.0;
double ageSum = 0.0;
for (int i = 0; i < position; i++) {
if (p1[total].getAge() < p2[total].getAge()) {
ageSum = p2[total].getAge() - p1[total].getAge();
} else {
ageSum = p1[total].getAge() - p2[total].getAge();
}
ageSum = ageDif;
}
}
}
Is this have something to do with the name of the 'Couple' file or how
I call the class. I am getting an 'Undeclared Variable' error.
You defined c inside your main() method. Therefore it is not visible in your other methods. Either pass c as a parameter to your other methods or make it a (static) property of the AgencyInterFace class instead of a local variable of main().
USING STATIC METHODS
If you want to call a method of the class, e.g. test(int position), without creating a variable c, you need to make this method static:
public static String test(int pos) {
if (pos!=-1) {
if (p1[pos].getAge()<p2[pos].getAge()) return("GOOD FOR "+p2[pos].getName()+"!");
else return("GOOD FOR"+p1[pos].getName()+"!");
}
return "error";
}
In this case, your arrays p1[] and p2[] would also need to be static --> they would only be created one time.
And example for making your arrays static:
private static Person[] p1 = new Person[MAX],
p2 = new Person[MAX];
Now you can call this method of the class using Couple.test(position) and it will return a String.
USING NON-STATIC METHODS
If you want to create multiple references of the class Couple, in that p1[] and p2[] should contain different values, you need to create a reference of the class Couple.
You can implement this by telling the program, what c is:
Couple c = new Couple();
Edit:
I see that you have created a couple, but not at the right place. If you create your couple inside of the main() method, you cannot use it anywhere except in this method. You should declare it in your class:
public class AgencyInterFace {
private static Couple c = new Couple(); //<-- here
// main-method
// other methods
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I wrote a simple calculation program. I want users to enter their request as 12+12 and return the answer. I used StringTokenizer, but I got an error and it doesn't show me any result. There was a mention that Calc is a superclass and MinusCalc and PlusCalc are subclasses. Does anyone have any idea?
void inputLineData() { // This is just the function that use for this case
System.out.println(" Plz enter your all numbers");
String strAll = key.next();
StringTokenizer st = new StringTokenizer(strAll);
int n1 = Integer.parseInt(st.nextToken());
String str = st.nextToken();
int n2 = Integer.parseInt(st.nextToken());
switch (str.charAt(0)) {
case '+':
PlusCalc P = new PlusCalc(n1, n2);
listCalc[indexCalc] = P;
indexCalc++;
break;
case '-':
MinusCalc M = new MinusCalc(n1, n2);
listCalc[indexCalc] = M;
indexCalc++;
break;
default:
System.out.println("Error!");
}
}
And this is MinusCalc class:
public class MinusCalc extends Calc {
#Override
public int func(){
return n1 - n2 ;
}
public MinusCalc(int n1, int n2) {
super(n1, n2);
}
}
And this is PlusCalc class:
public class PlusCalc extends Calc {
#Override
public int func(){
return n1 + n2;
}
public PlusCalc(int n1, int n2) {
super(n1, n2);
}
}
And this is Calc class:
public abstract class Calc {
public Calc(int n1, int n2) { // constructor with parameters!!
this.n1 = n1;
this.n2 = n2;
}
int n1,n2;
public abstract int func();
}
Assuming your input is correct the following might help you (if you have more operators just append to the list). The true in the parameter means you want to use the given operator as a delimiter as well as an operator, meaning it will be returned as a token too.
StringTokenizer st = new StringTokenizer(strAll, "+-*/", true);
if (st.countTokens() == 3) {
int operand1 = Integer.parseInt(st.nextToken().trim());
String operator = st.nextToken();
int operand2 = Integer.parseInt(st.nextToken().trim());
switch (operator.charAt(0)) {
case '+':
PlusCalc P = new PlusCalc(operand1, operand2);
listCalc[indexCalc] = P;
indexCalc++;
break;
case '-':
MinusCalc M = new MinusCalc(operand1, operand2);
listCalc[indexCalc] = M;
indexCalc++;
break;
default:
System.out.println("Error!");
}
}
NOTE: try to use another option mentioned in the comments instead of StringTokenizer if you have not to.
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.
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();
}
This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).