Using Scanner Class within a method - java

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);

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

"cannot find symbol" error when invoking a method using reference of class

I feel as if this is super simple but I cant get this to work. I am trying to use this:
import java.util.Scanner;
import java.lang.Math;
public class SammysRentalPriceWithMethods
{
public static void main(String[] args)
{
Rental rental = new Rental();
SammysRentalPriceWithMethods SRPWM = new SammysRentalPriceWithMethods();
getLogo();
getContractNum();
getHoursAndMinutes();
}
public static void getLogo()
{
rental.setlogo();
}
public static void getContractNum()
{
rental.setContractNumber();
}
public static void getHoursAndMinutes()
{
rental.setHoursAndMinutes();
}
}
to call this class and the methods contained inside:
import java.util.Scanner;
import java.lang.Math;
public class Rental
{
public final int minutes = 60;
public final double hourlyRate = 40.0;
private static String contractNum;
private static double hours;
private static int minutes2;
private static double price;
Scanner Input = new Scanner(System.in);
public static void setlogo()
{
System.out.println("*********************************");
System.out.println("*Sammy's makes it fun in the sun*");
System.out.println("*********************************");
}
public static void setContractNumber()
{
Scanner Input = new Scanner(System.in);
System.out.println("Please enter your contract number.");
contractNum = Input.nextLine();
}
public static void setHoursAndMinutes()
{
int timeOver;
Scanner Input2 = new Scanner(System.in);
System.out.println("Please enter the amount of time in minutes you rented the equipment.");
minutes2 = Input2.nextInt();
if (minutes2 > 60)
{hours = (minutes2/60);
price = (hours * 40);
timeOver = (minutes2%60);
price = (price + timeOver);
System.out.println("You rented the equipment for " + hours + " hours and " + timeOver + " minutes.");
System.out.println("Your total price is: " + price);
}
else if (minutes2 < 60)
{
price = (minutes2 * 1);
System.out.println(price);
}
}
}
but the compiler is saying "error: cannot find symbol" on every reference of rental in the SRPWM class. I already called the class in the main method. Any ideas?
The compiler is right.
The scope of the variables rental and SRPWM is restricted to the main method.
Either you pass the attributes to the methods of the class or you make them static fields of SammysRentalPriceWithMethods.
Because rental is declared in your main method, it will only be visible in that method. You should consider declaring this variable at the class level.
You need to declare the Rental class variable outside the main() function. If you declare it inside the main(), then you won't be able to use it in other functions. So, make your Rental variable global.
New file should be this:
import java.util.Scanner;
import java.lang.Math;
public class SammysRentalPriceWithMethods {
Rental rental = new Rental();
public static void main(String[] args) {
SammysRentalPriceWithMethods SRPWM = new SammysRentalPriceWithMethods();
getLogo();
getContractNum();
getHoursAndMinutes();
}
public static void getLogo() {
rental.setlogo();
}
public static void getContractNum() {
rental.setContractNumber();
}
public static void getHoursAndMinutes() {
rental.setHoursAndMinutes();
}
}
The problem is you are mixing both static and non-static members and invoking them inside your SammysRentalPriceWithMethods class, so change the class as shown in the below code with comments:
public class SammysRentalPriceWithMethods {
private Rental rental;
//Use constructor to inject Rental object
public SammysRentalPriceWithMethods(Rental rental) {
this.rental = rental;
}
public static void main(String[] args) {
//create Rental object
Rental rental = new Rental();
SammysRentalPriceWithMethods srpwm =new SammysRentalPriceWithMethods();
//invoke methods using srpwm reference
srpwm.getLogo();
srpwm.getContractNum();
srpwm.getHoursAndMinutes();
}
public void getLogo() {
rental.setlogo();
}
public void getContractNum() {
rental.setContractNumber();
}
public void getHoursAndMinutes() {
rental.setHoursAndMinutes();
}
}
You need to remember the following basics:
(1) Call static members of a class using classname and . operator (if you want to call static members within static methods you call them without classname and .)
(2) Call non-static members using the object and . operator
(3) Name the variables, method names with camel case (starting letter in lower case)

Java objects of classes not returning the same values

I am creating an object of a class from 2 separate classes and both objects are returning different values for the same method. I suspect it may be an issue with the while loop but here are the classes. The main class works, the setup class is the class that is being turned into and object and the game loop class has the object that doesn't return the right values. it returns the values defined at the beginning of setup and not the modified versions.
import java.util.Scanner;
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop();
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
import java.util.Scanner;
public class setup {
static Scanner input = new Scanner(System.in);
String goverment;
int happyness;
double money;
int population = 1000000;
public setup()
{
}
public void statsSetup()
{
System.out.println("Choose a goverment: 1. democracy 2. monarchy 3. dictatorship");
goverment = input.nextLine();
if (goverment.equals("1"))
{
happyness = 75;
money = 250000.0;
}
else if (goverment.equals("2"))
{
happyness = 50;
money = 500000.0;
}
else if (goverment.equals("3"))
{
happyness = 25;
money = 750000.0;
}
else
{
System.out.println("ENTER A VALID VALUE");
}
}
public int getHappyness()
{
return happyness;
}
public double getMoney()
{
return money;
}
public int getPopulation()
{
return population;
}
}
import java.util.Scanner;
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop()
{
}
setup setupGov = new setup();
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
You are creating two different instances of class setup. One is created directly in main function and other is created in gameLoop object. They do not share their attributes so methods may return different value. Every time you use 'new' operator, a new instance of class is created with it's own attributes (only static member are shared since static member belongs to class instead of instances). If you want to have same instances you could write:
public class gameLoop
{
static Scanner input = new Scanner(System.in);
static int turn = 0;
int happyness;
double money;
int population;
public gameLoop(setup setupGov)
{
this.setupGov = setupGov;
}
setup setupGov;
public static void main(String[] args)
{
}
public void loop()
{
while (true)
{
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
}
And in main:
public class MainClass {
static Scanner input = new Scanner(System.in);
//String x = input.nextLine();
public static void main(String[] args)
{
setup setupGov = new setup();
gameLoop gameLoop = new gameLoop(setupGov);
setupGov.statsSetup();
System.out.println("happyness: " + setupGov.getHappyness() + " money: £" + setupGov.getMoney() + " population: " + setupGov.getPopulation());
gameLoop.loop();
}
}
Now both of objects setupGov will be the same instance.
Please note:
It is good practice to have class name written with capitalized first letter eg. GameLoop instead of gameLoop
I don't really understand what you're trying to do or what the question is, but in your main class you have an object with the same exact name of the class.
gameLoop gameLoop = new gameLoop();
I don't know if that's the exact cause of your problem, but I'm almost sure that that isn't supposed to be like that.

Identifier expected, 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 + "!");
}
}

Nothing being printed out

I'm very new to programming and I'm having a bit of trouble. Basically what I'm trying to do is to have the findCar method loop through the LinkedList called cars and have it printout the ids of the car objects. It will compile however nothing is being printed, could someone please explain why this is?
Here is the main class
import java.io.*;
import java.util.*;
public class CarManger {
private LinkedList<Car> cars = new LinkedList<Car>();
public void setup()
{
cars.add(new Car(1));
cars.add(new Car(2));
cars.add(new Car(3));
}
public void main() {
char choice;
while ((choice = readChoice()) !='x' ) {
switch(choice) {
case 'a': findCar(); break;
}
}
}
private char readChoice() {
System.out.print("Your choice: ");
return In.nextChar();
}
public void findCar()
{
for (Car i: cars)
{
int value = i.getId();
System.out.println(value);
}
}
}
And here is the Car Object
public class Car {
private int id;
public Car(int id)
{
this.id = id;
}
public int getId() {
return this.id;
}
}
And here is the In class for gathering input
import java.util.*;
public class In
{ private static Scanner in = new Scanner(System.in);
public static String nextLine()
{ return in.nextLine(); }
public static char nextChar()
{ return in.nextLine().charAt(0); }
public static int nextInt()
{ int i = in.nextInt();
in.nextLine();
return i; }
public static double nextDouble()
{ double d = in.nextDouble();
in.nextLine();
return d; }
Here is also the revised code
import java.io.*;
import java.util.*;
public class CarManger {
private LinkedList<Car> cars = new LinkedList<Car>();
public static void main(String [ ] args) {
CarManager carManager = new CarManager();
}
public CarManager () {
setup();
main();
}
Your setup() method is never called, and so no Cars appear to be added to your cars list.
Note that your main method needs to be static and to have an array of Strings parameter (unless this is not the starting point main method for your program). Without a main method, the program will compile, but won't run.
I suggest that you create a valid main method:
public static void main(String[] args) {
}
And inside create a CarManager object, call setup() on it, etc...
Note: if I had a method called findCar(), I'd probably have it accept a parameter, here, the best parameter would likely be an int to represent the Car's id number, I'd declare the method to return a Car object, and inside the method body, I'd search for a Car whose id matched that of the method parameter. The method signature would look something like this:
public Car findCar(int id) {
// TODO:
// write code to loop through the cars list
// if we find a car whose getId() matches our parameter id int
// return it!
}
Your main method would look like this:
public static void main(String[] args) {
CarManager carManager = new CarManager();
// here you'd call methods on carManager
// for instance if CarManager had an addCar(...) method
Car car = new Car(4);
carManager.addCar(car);
}
Note, I'm not calling your current setup() method or readChoice() because they don't look right to me, but without your specific assignment requirements, it's hard to guess.
You are not defining the main method correctly. It should be like this:
public static void main(String [ ] args)
Also, you should call the setup() method to load the array of cars.

Categories