Identifier expected, Java - java

I'm trying to debug this simple application for an assignment, but I'm not sure why it won't compile...
import java.util.Scanner;
public class DebugThree3
{
public static void main(String[] args)
{
String name;
getName();
displayGreeting(name);
}
public String getName(name)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
name = input.nextLine();
return name;
}
public static void displayGreeting()
{
System.out.println("Hello, " + name + "!");
}
}
Attempting to compile tells me an identifier is expected on line 12, public String getName(name). Can anyone tell me what I'm missing here?
Thanks

You need to specify the Type of the parameter that a method accepts
public String getName(String name)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
name = input.nextLine();
return name;
}
Pass a parameter to the getname function in the main function.
Like SURESH pointed out, the getname function needs to be marked as static. Else, you will need to create an object of the class before you access the methods in it.

I took the liberty to fix your program in two standard ways of doing what you're trying to do.
Currently you're not passing name and you probably assume it exists in scopes in which it does not.
I also moved the redundant put-something-in-a-parameter-and-return behaviour in:
String name = input.nextLine()
return name;
And only left:
return input.nextLine();
First way is passing name between functions as a parameter, specifying its type:
import java.util.Scanner;
public class DebugThree3
{
public static void main(String[] args)
{
String name = getName();
displayGreeting(name);
}
public String getName()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
return input.nextLine();
}
public static void displayGreeting(String name)
{
System.out.println("Hello, " + name + "!");
}
}
Second way is having name as a static class member:
import java.util.Scanner;
public class DebugThree3
{
String name;
public static void main(String[] args)
{
getName();
displayGreeting();
}
public String getName()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter name: ");
DebugThree3.name = input.nextLine();
}
public static void displayGreeting()
{
System.out.println("Hello, " + DebugThree3.name + "!");
}
}

Related

How would I make a loop in java that will ask the user to pick a class from the array list and if they enter an invalid value to ask again?

My code:
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
Scanner ask = new Scanner(System.in);
System.out.println("Enter the class for Carmilla\n");
String nameC = ask.next();
Boolean temp;
I was attempting to do a while loop but I was not sure what conditions to use
while(temp = true) {
if(nameC.equalsIgnoreCase("theif")) {
Carmilla.sethClass(nameC);
temp = false;;
break;
} else {
System.out.println("Invalid class try again");
}
}
System.out.println(Carmilla);
Hero class just sets the values for everything, I would use (depending on the name of the person I'm calling) `Carmilla.sethClass(nameC)', which just sets the name of the chosen class to the hero class.
I want to ask the user what class they would like to set for each person(they are the names stated with Hero in front of them)and if the user does not type one of the classNames value then they are told that its an invalid statement and to try again, which will then ask again what class they want for (in this example) Carmilla.
Here is one way to accomplish it.
The class with main method is below. A few notes about it. First, I made the Party class just an ArrayList of Hero objects, since I'm assuming that a party is just a collection of heroes. This makes asking names for each of the four heroes easier because we can loop through the party list.
Next, I moved the instantiation of the Hero objects into the initialization of the party so that the list already contains our Hero objects.
I utilized a for-each loop to check and assign classes to each Hero and a while loop to redirect the user back if they entered an invalid class. I check whether the class is valid using the boolean validClass. The final output of running this is shown at the very bottom.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
List<Hero> party = Arrays.asList(new Hero("Carmilla"),
new Hero("Alucard"),
new Hero("steve"),
new Hero("sypha"));
String[] classNames = { "theif", "warrior", "wizard", "steve", "bard" };
Scanner ask = new Scanner(System.in);
for (Hero hero : party) {
if (hero.getHclass()
.equals("Default")) {
boolean validClass = false;
while (!validClass) {
System.out.println("Enter the class for " + hero.getName());
String hClass = ask.nextLine();
for (String name : classNames) {
if (hClass.equals(name)) {
validClass = true;
}
}
if (validClass) {
hero.setHclass(hClass);
}
}
}
}
party.forEach(hero -> {
System.out.println(hero.getName() + " has class " + hero.getHclass());
});
}
}
The Hero class:
public class Hero {
private String name;
private String hclass = "Default";
public Hero(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHclass() {
return hclass;
}
public void setHclass(String hclass) {
this.hclass = hclass;
}
}
Output:
Use for-each loop to match the entered name against the classNames
Code:
import java.util.Scanner;
import java.io.*;
//Hero class replace with your class
class Hero{
String name="";
String className="";
public Hero(){}
public Hero(String name){
this.name=name;
}
public void sethClass(String className){
this.className=className;
}
#Override
public String toString(){
return "Name : "+name+" className : "+className;
}
}
public class PartyTest {
public static void main(String[] args) throws IOException{
//Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
//Scanner ask = new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the class for Carmilla\n");
boolean matched=false;
while(!matched) {
String nameC = br.readLine();
//Use for-each loop to match the entered name
for(String name : classNames){
if(nameC.equalsIgnoreCase(name)) {
Carmilla.sethClass(nameC);
matched=true;//Matched
break;
}
}
if(matched)break;
System.out.println("Invalid class try again\n");
}
System.out.println(Carmilla);
}
}
OUTPUT:
$ javac PartyTest.java && java PartyTest
The avaliable classes are:
theif
warrior
wizard
steve
bard
Enter the class for Carmilla
blaba
Invalid class try again
qwertr
Invalid class try again
Wizard
Name : Carmilla className : Wizard

Using Scanner Class within a method

import java.util.Scanner;
public class Tutorials {
public static void main(String[] args) {
Car Vehicle = new Car();
Vehicle.supboys();
}
}
import java.util.Scanner;
public class Car {
private String Vehicle;
public Car(String name) {
Vehicle=name;
}
Car() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setName (String name) {
Vehicle=name;
}
public String getName (){
return Vehicle;
}
public void saying(){
System.out.printf("Vehicle Brand is called %s\n ", getName());
}
public void supboys() {
Scanner Boyz = new Scanner(System.in);
System.out.println ("Your New Car is " + Boyz);
}
}
I am new to programming so I wanted to some practise, regarding constructors. I wanted to try doing a scanner class for this program but cant seem to get it to work. The program does not give a proper error message to me either. Does anyone have any suggestions? (Apologies for the messy code)
You need to use Scanner's methods for Scanner to work the way you want. You would want to do something like this:
Scanner Boyz = new Scanner(System.in);
String shoutout = Boyz.nextLine();
System.out.println ("Your New Car is " + shoutout);

validate private variable of another class when giving input

hello I have written code where it takes book details using setter method and displaying details using getter method. When user enters the input it has to enter three details.
Book NameBook PriceAuthor Name
I want to check if user has given any negative value or Zero value in Book Price.
How do I do that? Below is the code. I am practicing Encapsulation problem
//Book.java file
class Book
{
private String bookName;
private int bookPrice;
private String authorName;
public String getBookName()
{
return bookName;
}
public int getBookPrice()
{
return bookPrice;
}
public String getAuthorName()
{
return authorName;
}
public void setBookName(String a)
{
bookName=a;
}
public void setBookPrice(int b)
{
bookPrice=b;
}
public void setAuthorName(String c)
{
authorName=c;
}
}
//TestBook.java file
import java.util.*;
class TestBook
{
public static void main(String args[])
{
Book bobj = new Book();
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter the Book name:");
bobj.setBookName(sc.nextLine());
System.out.println("Enter the price:");
bobj.setBookPrice(sc.nextInt());
sc.nextLine();
System.out.println("Enter the Author name:");
bobj.setAuthorName(sc.nextLine());
System.out.println();
System.out.println("Book Details");
System.out.println("Book Name :"+bobj.getBookName());
System.out.println("Book Price :"+bobj.getBookPrice());//should not be -ve or 0
System.out.println("Author Name :"+bobj.getAuthorName());
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}
}
You should put this check in your setter method to check if it is greater than zero. For example:
public void setBookPrice(int b)
{
if(b>0)
bookPrice=b;
else
{
throw new IllegalArgumentException("b must be positive")
}
}
Above code will prevent setting of negative and zero price. You can replace exception throwing code with your own handling.
If you are practising encapsulation I suggest creating a specific validation method for the price so this can be easily modified without changing the public interface.
public boolean isValidPrice() {
return bookPrice > 0;
}
This can now be checked with
if (!bobj.isValidPrice()) {
//error handling
}
And if the validation rules for price would change the calling code will remain unchaged

I'm trying to use a method to print another method

public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String q = null, s = "nul";
userName(q);
userGender(s);
print(userName(q));
print(userGender(s)); // how to achieve something like this?
}
public static void userName(String x) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String n = sc.nextLine();
}
public static void userGender(String y) {
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
String v = sd.next().toString();
}
public static void print(String a) {
System.out.println(a);
}
So I was trying to make it so that a method would be used to print another method after they were done executing but I couldn't get the desired result and it gave an error.
The method print works fine, it takes a String and return nothing
public static void print(String a)
{
System.out.println(a);
}
However, your method userGender and userName returns nothing, so when you are feeding print with a method that isn't returning a string, it will produce an compile-time error. You want to do something similar to:
public static String userGender(String y){
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
return sd.next().toString();
}
I haven't tested it, as your logic is unclear to me, but this is probably why your IDE is complaining.
Your method needs to return something. You are declaring your method like this: public static void userGender(String y) the void means that your method won't return anything. But since you want that the method returns a String you need to tell this in the method signature.
Your code could look like this:
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
try(Scanner sc = new Scanner(System.in)){ // this is try resource see which will close your resource once you are done in the try block see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
System.out.print("Enter name: ");
return sc.next();
}
}
public static String userGender() {
try(Scanner sc = new Scanner(System.in)) {
System.out.print("Enter Gender: ");
return sc.next();
}
}
public static void print(String a) {
System.out.println(a);
}
You don't need to use toString() since the next returns already a String. Also you can use the same variable name in different methods. And really important you need to close the Scanner again, otherwise it will consume endless resources.
Like #reebow and #Kerry Gougeon both pointed out that your method is looking to return something so you make it public static String userName() or public static String userName(String s).
If you're wanting to user Scanner then you're going to have to declare Scanner globally, otherwise it will throw a NoSuchElementExcpetion
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
System.out.print("Enter name: ");
return sc.next();
}
public static String userGender() {
System.out.print("Enter Gender: ");
return sc.next();
}
public static void print(String a) {
System.out.println(a);
}
If you're not using Scanner then you can just return the String that you passed to the method.
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String a = null, b ="nul";
print(userName(a));
print(userGender(b));
}
public static String userName(String a) {
System.out.print("Enter name: ");
return a;
}
public static String userGender(String b) {
System.out.print("Enter Gender: ");
return b;
}
public static void print(String a) {
System.out.println(a);
}

I compile the below java program in command prompt but it's showing an error and I cannot fix it

I am compiling all my java program in cmd but when I run below program, it's showing an error like "reached end of file while parsing" ! And when I try to run it in eclipse it's showing red underline below bold code that is methods and main methods.
import java.io.*;
class empl{
int empno;
String name;
String position;
int ph;
public void getdata()throws IOException{
DataInputStream e = new DataInputStream(System.in);
System.out.println("Enter name: ");
empno = Integer.parseInt(e.readLine());
System.out.println("Enter your name: ");
name = e.readLine();
System.out.println("Enter the employee position: ");
position=e.readLine();
System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());
}
public void displaydata() {
System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);
}
class manager extends empl{
int salary;
String secname;
public void getdata() throws IOException{
getdata();
DataInputStream e= new DataInputStream(System.in);
System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());
System.out.println("Enter second name: ");
secname= e.readLine();
}
public void displaydata(){
displaydata();
System.out.println(salary+"\t"+secname);
}
class inheritt{
public static void **main(String []args)throws IOException**{
inheritt e1= new inheritt();
inheritt e2= new inheritt();
**e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();**
}
Only top level classes can have static methods: Declare inheritt as a top level class rather than an inner class
public class inheritt {
public static void main(String[] args) throws IOException {
...
}
}
**e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();**
e1 and e2 are of inheritt type and don't have the getdata() and displaydata() methods
Try this code... I think this may be what you want. I fixed some of the brackets, not really sure of what goes where. I also, made inheritt extends manager. I think that's what you want. You may be wanting to show the inheritance chain of the classes.
import java.io.*;
class empl{
int empno;
String name;
String position;
int ph;
public void getdata()throws IOException{
DataInputStream e = new DataInputStream(System.in);
System.out.println("Enter name: ");
empno = Integer.parseInt(e.readLine());
System.out.println("Enter your name: ");
name = e.readLine();
System.out.println("Enter the employee position: ");
position=e.readLine();
System.out.println("Enter the phone number: ");
ph = Integer.parseInt(e.readLine());
}
public void displaydata() {
System.out.println(empno+"\t"+name+"\t"+position+"\t"+ph);
}
}
class manager extends empl{
int salary;
String secname;
public void getdata() throws IOException{
getdata();
DataInputStream e= new DataInputStream(System.in);
System.out.println("Enter salary: ");
salary=Integer.parseInt(e.readLine());
System.out.println("Enter second name: ");
secname= e.readLine();
}
public void displaydata(){
super.displaydata();
System.out.println(salary+"\t"+secname);
}
class inheritt extends manager {
public static void **main(String []args)throws IOException**{
inheritt e1= new inheritt();
inheritt e2= new inheritt();
e1.getdata();
e2.getdata();
e1.displaydata();
e2.displaydata();
}

Categories