I am having trouble clearing the following error '(' or '[' expected on the second line of case 2 and case 3. The code I have written is newAnimal.displayInfo();
I am not sure why I get this error on case 2 and 3 but not case 1. Not sure what I am doing wrong. Any assistance/guidance will be appreciated.
Here is what the code looks like:
package animalinfo;
import java.util.Scanner;
public class AnimalInfo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner input = new Scanner (System.in);
Animal newAnimal;
int quit = 4;
while(-4 != quit);
{
System.out.println("\n1) Camel" +
"\n2)Penguin" +
"\n3) Tortoise" +
"\n4) Exit Program.");
System.out.print("Please select an amimalfrom the list.");
int choice = input.nextInt();
switch (choice)
{
case 1:
newAnimal = new Camel();
newAnimal.displayInfo();
break;
case 2:
newAnimal = new Penguin
newAnimal.displayInfo();
break;
case 3:
newAnimal = new Tortoise
newAnimal.displayInfo();
break;
case 4:
System.out.println ("Thank you for making your selections.");
break;
}
}
}
}
It seems like you're missing parentheses after creating the new objects. So this:
newAnimal = new Penguin
should become this:
newAnimal = new Penguin();
This is because you're setting newAnimal to a new instance of a Penguin object, and to create that new instance you must call the constructor of the Penguin class to create the object.
Also, as Jurko stated, your while loop is set up incorrectly.
while(-4 != quit);
You must remove the semicolon, otherwise the loop will indefinitely run without executing the code you have underneath it. The correct syntax for a while loop is
while (-4 != quit) {
// Code to repeat here
}
while(-4 != quit);
Get rid of the semicolon, should just be
while (-4 != quit)
{
/*Code here*/
}
and yes, when you have new Penguin and new Tortoise, you are missing the parentheses and semicolon
Related
I am trying to create an issue tracking System, but I am having a bit of a problem, every time I run the code, it does not come back to the menu, it just loops. I want my code to come back to the menu whenever i describe my issue.
package com.company.TrackingSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
private void menu() {
boolean is = true;
System.out.println("---Menu---");
System.out.println(
"1.Create new Issue\n" +
"2.Mark Issue as solved\n" +
"3.View unsolved Issues\n" +
"4.View solved Issues\n" +
"5.Exit\n"
);
}
}
My tracking class
package com.company.TrackingSystem;
public class TrackingSystem {
private String createIssue;
private boolean issueSolved;
public TrackingSystem(String createIssue, boolean issueSolved) {
this.createIssue = createIssue;
this.issueSolved = issueSolved;
}
public String getCreateIssue() {
return createIssue;
}
public void setCreateIssue(String createIssue) {
this.createIssue = createIssue;
}
public boolean isIssueSolved() {
return issueSolved;
}
public void setIssueSolved(boolean issueSolved) {
this.issueSolved = issueSolved;
}
}
Example output:
---Menu---
1.Create new Issue
2.Mark Issue as solved
3.View unsolved Issues
4.View solved Issues
5.Exit
Select option >> 1
*** Create an Issue***
Describe your Issue:
*** Create an Issue***
Describe your Issue:
as
*** Create an Issue***
Describe your Issue:
sa
*** Create an Issue***
Describe your Issue:
as
Let's look at this function:
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
Pay special attention to the loop condition: while(is). You declare bool is = true; but you never change it to false inside the loop. This means the loop will continue forever.
To fix this, you have to make some decisions. First, do you really want to continue looping here? Is your intention to allow the user to enter as many issues as they want? Or do you want to create only a single issue then return to the menu. If the former, then you need to figure out how the user will tell the program that they are finished entering issues. You can use this to stop the loop. If the later, then just remove the loop.
Now let's look at main():
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
Even after you solve the problem with your code to create an issue, you will run the program and it will exit after one action. This is because you do not loop in main(). You need to add a loop here that repeats the following steps:
Print the menu.
Get the user's choice.
Perform the action for that choice
Repeat to step 1.
Each of these steps can be a method so that you can keep main() very short. Note how the first 3 steps are inside a loop. I think this is what you were trying to do with the loop for creating a new item, but somehow put the loop in the wrong place. As you can see here, by writing out the steps in words, we get a clear idea of how to organize the code. Doing this is a great tool when writing a computer program.
I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception
java.util.NoSuchElementException
for sample input
5
1 2 3 4 5
here first line contains number of elements (in this case its 5),and next line contains elements.
while taking input inside the for loop in the class Election ,i am getting exception.
I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.
import java.io.*;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
input.nextLine();
Election obj = new Election(n);
obj.getVotes();
}
}
class Election {
int n,v1,v2,v3,v4,v5,d;
public Election(int n) {
this.n = n;
v1=v2=v3=v4=v5=d=0;
}
public void getVotes() {
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i < 1 ; i++) {
int var = sc.nextInt();
switch(var) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
}
Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.
Here is a simple deviation of the code you provided, but reaches the desired result!
I'll walk you through this:
public class MyTest {
public static void main(String[] args) {
//First of all, we need an instance of an Election-type object, so
//that we can call its methods and get votes from users.
Election e = new Election();
//Now we can easily call the method getVotes(), as defined in Election class.
//What happens here, is that the program will 'jump' to the getVotes() method
//and it will execute every line of code in that method. Then it will
//'return' to where it 'left off' in the main() method. Since getVotes()
//is of type 'void', it will not return anything. It will just 'jump' back.
e.getVotes();
//Now, you can use testResult() method, to see the values of the variables.
e.testResult();
}
}
Now, let's take a look at the class Election and how it works.
public class Election {
private final int VOTES_NUM = 1;
private int v1,v2,v3,v4,v5,d;
public Election() {
v1=v2=v3=v4=v5=d=0;
//print now, just to show that all variables = 0
testResult();
}
//Simple method that prints value of each variable. We use this for testing
public void testResult(){
System.out.println("v1 = "+v1);
System.out.println("v2 = "+v2);
System.out.println("v3 = "+v3);
System.out.println("v4 = "+v4);
System.out.println("v5 = "+v5);
System.out.println("d = "+d);
}
private int getInput(){
//First of all, we need a Scanner to take user input.
//You do that in your own code too. We simply move it in this method instead.
Scanner input = new Scanner(System.in);
//You also need variable to hold the user input.
//(Always give meaningful names to all entities)
int userInput;
System.out.print("Please enter vote number here: ");
//the next part has to be in a try-catch block,
//to avoid exceptions like InputMismatchException, etc..
try{
//Get user input
userInput = input.nextInt();
}
//If user enters letter, or symbol, or something else that isn't an integer,
//then inform them of the mistake they made and recursively call this method,
//until they get it right!
catch (InputMismatchException ime){
System.out.println("Please enter only a single number");
return getInput();
}
//If all goes well, return the user input
return userInput;
}
public void getVotes() {
//'VOTES_NUM' is a constant that defines the times the
//loop will iterate (like Macros in 'C')
for(int x=0; x<VOTES_NUM; x++)
int n = getInput();
//then let the switch statement increment one of the variables
switch(userInput) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.
I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:
public static void main(String...args){
Election election = new Election(10);
election.getVotes();
System.out.println(election.v1);
System.out.println(election.v2);
System.out.println(election.v3);
System.out.println(election.v4);
System.out.println(election.v5);
System.out.println(election.d);
}
My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:
2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d
I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)
I am doing a project (based on a tutorial). I have a switch statement and for each case, there's a default in case the user input is invalid, and I write on the console "Sorry, I do not understand your request". However, if the user instead of writing whatever, writes "exit", the program should end without that "I don't understand request" sentence showing up.
This is stated in my IF statement in the beginning. What my current project does at the moment when I type "exit" is showing that line and then stopping. I don't understand how the program completely ignores that IF statement in the beginning.
public class MainGame {
public static GameSave gameSave = new GameSave();
public static String user = "";
public static Scanner scanner = new Scanner(System.in);
public static String question;
public static int relationshipPoints;
public static void main(String[] args) {
Random random = new Random();
question = gameSave.loadGame();
// relationshipPoints = gameSave.loadPoints();
RelationshipPoints points = new RelationshipPoints();
System.out.println("\n\t*** TEXT_GAME: FIRSTDATE ***\n");
System.out.println("-You can exit the game at any time by typing 'exit'.-\n\n");
while (true) {
if (user.equalsIgnoreCase("exit")) {
System.exit(1);
break;
} else {
switch (question) {
[...]
case "2":
switch (user = scanner.next()) {
case "1":
System.out.println("\n\nThe guy you met last night was nice. You want to "
+ "get back into contact with him. Why don't you check your phone for a number?");
question = "2A";
gameSave.saveGame("2A");
break;
case "2":
System.out.println("\n\n");
question = "0";
break;
default:
System.out.println("\nI do not understand your request.\n");
question = "2";
break;
}
break;
case "2A": [...]
Try replacing your while(true) {...} with while ((user = scanner.next() != null) { ... }
It looks like you are trying to access the "user" data without first setting it.
user = scanner.nextLine(); insert this line just after entering in while loop. your problem occurs as you are checking user equal to exit but user has nothing so control goes to else portion.
import java.util.Scanner;
public class MainMenu {
public MainMenu(){
int x = 1;
Scanner menuIn = new Scanner(System.in);
while ( x == 1 ){
String pick = "0";
System.out.println("--== Household Admin v1.0 ==--");
System.out.println("(A)dd Resident");
System.out.println("(R)emove Resident");
System.out.println("(L)ist Resident(s)");
System.out.println("pick = " + pick);
System.out.print("#: ");
pick = menuIn.nextLine();
System.out.println("pick = " + pick);
switch (pick) {
case "A":
case "a":
Resident.residentList.add( Resident.newResident() );
break;
case "R":
case "r":
break;
case "L":
case "l":
break;
case "Q":
case "q":
x = 0;
break;
default:
System.out.println("WRONG! Try again.");
break;
}
}
menuIn.close();
}
}
The first time through the loop everything works as expected. The second time throught the loop I am getting:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at household.MainMenu.(MainMenu.java:26)
at household.MyFirstGame.main(MyFirstGame.java:7)
I am not sure how to "reset" the scanner object as to be able to reuse it again.
You have your whole code in constructor of MainMenu in which you are closing the scanner by calling menuIn.close(); which is the root cause.
It seems you are creating new instances of MainMenu from main method inside MyFirstGame. Now if you call .close() on scanner object, it closes the underlying stream. So your first object gets created successfully. But when you try to instantiate second object of MainMenu you get this exception since System.in stream has been closed.
Ideally you should use single scanner object for reading user inputs. Instead of creating new scanner object in constructor every time, just create a single scanner object in main method and pass it as argument to the constructor. Something like below.
inside MyFirstGame.main
Scanner menuIn = new Scanner(System.in);
MainMenu mainMenu1= new MainMenu(menuIn);
MainMenu mainMenu2= new MainMenu(menuIn);
//.... and So on
//and close scanner object here once you have created all reaquired object.
menuIn .close();
In you MainMenu change constructor to
public MainMenu(Scanner menuIn ){
And Remove below lines from the constructor
//Scanner menuIn = new Scanner(System.in);
//menuIn.close();
why am i getting an array index out of bounds for this code?
i am getting an error exception in thread MainJava.Lang.ArrayIndexOutOfBoundsException
//java calculator
public class Calculator
{
public static void main(String[] args)
{
double a,b,m;
char c;
a=Double.parseDouble(args[0]);//taking input from command line
c=args[1].charAt(0);
b=Double.parseDouble(args[2]);
switch(c)//using switch to perform calc operations
{
case('+'):
m=a+b;
System.out.println(args[0]+args[1]+args[2]+"="+m);
break;
case('-'):
m=a-b;
System.out.println(args[0]+args[1]+args[2]+"="+m);
break;
case('*'):
m=a*b;
System.out.println(args[0]+args[1]+args[2]+"="+m);
break;
case('/'):
m=a/b;
System.out.println(args[0]+args[1]+args[2]+"="+m);
break;
default:
System.out.println("invalid option");
}
}
}
The code works fine if you pass it command line parameters.
You can add parameters to the class by right clicking the Calculator.java file inside eclipse and going to run as > run configurations. Inside there you can click on the parameters tab and add the parameters manually to the program arguements.
Alternatively, you can run this on the command prompt and pass the parameters that way.
On command line: java Calculator 5 + 1
More details are available here: https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
If you didn't intend to use command line arguements, you can use a Scanner object to set the variables a, b and c.
Scanner input = new Scanner(System.in);
a = input.nextDouble();
c = input.next().charAt(0);
In general, if you are going to write code that depends on command line input, its good practice to put some checks at the begining. For example,
if (args.length < 3)
System.out.println("Insufficient Arguments");
else {
//The rest of your code
}
To elaborate on the comments, it seems likely that your args array has length < 3. To confirm this, add System.out.println("args has length: " + args.length) as the first line of your main function and see what that prints. If the result is anything less than 3, then you're going to get an ArrayIndexOutOfBoundsException when you try to access args[2] (or the others if the length is even less).
More on ArrayIndexOutOfBoundsExceptions here: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
From there, the question becomes "what do I do if I don't have enough arguments?". Throwing an exception is probably not the idea answer. Some other options include:
Give the variables default variables (as the user didn't provide them), and continue as usual
Print a more descriptive error message and terminate
Java Code
Use scanner function to take input.
public class TestProgram {
public static void main(String args[]){
double a,b,m;
char c;
System.out.println("Enter the first number");
Scanner scanner = new Scanner(System.in);
a=Double.parseDouble(scanner.next());//taking input from command line
System.out.println("Enter the operation you want to perform + or - or * or /");
c=scanner.next().charAt(0);
System.out.println("Enter the second number");
b=Double.parseDouble(scanner.next());
switch(c)//using switch to perform calc operations
{
case('+'):
m=a+b;
System.out.println(a +"+"+ b +"="+ m);
break;
case('-'):
m=a-b;
System.out.println(a +"-"+ b +"="+ m);
break;
case('*'):
m=a*b;
System.out.println(a +"*"+ b +"="+ m);
break;
case('/'):
m=a/b;
System.out.println(a +"/"+ b +"="+ m);
break;
default:
System.out.println("invalid option");
}
}
}