I'm quite new to java so any input or help would be greatly appreciated. I'm trying to create a program that asks a user for a bunch of inputs (such as name, registration, colour, # of trips and odometer reading) for a Car class. I've created a car class, created an object of that class called carSample and given it the same variable names from my main method where i use a scanner to ask for name,registration etc...
However, this does not work and i receive the error:
TestCar.java:8: error: ';' expected
String carSample.name = input.nextLine();
Here is my code:
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Input name: ");
String carSample.name = input.nextLine();
System.out.print("Input registration: ");
String carSample.registration = input.nextLine();
System.out.print("Input colour: ");
String carSample.colour = input.nextLine();
System.out.print("Input trips: ");
int carSample.numberOfTrips = input.nextInt();
for (int i = 0; i < numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
}
car carSample = new car(); // Creates object of class Car
}
class car {
String name;
String registration;
String colour;
int numberOfTrips;
double odometerReading;
}
Any help would be greatly appreciated, thank you !
`import java.util.*;
class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
car carSample = new car(); // Creates object of class Car
System.out.print("Input name: ");
carSample.name = input.nextLine();
System.out.print("Input registration: ");
carSample.registration = input.nextLine();
System.out.print("Input colour: ");
carSample.colour = input.nextLine();
System.out.print("Input trips: ");
carSample.numberOfTrips = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
int odometerReading = input.nextInt();
}
}
}
class car {
String name;
String registration;
String colour;
int numberOfTrips;
double odometerReading;
}`
Try this out ... this should work ...
String carSample.name = input.nextLine();
carSample is declared in the car class. When you assign a value to a variable that is already declared, you don't have to specify the type. (it breaks when you do)
When you assign a value to a variable in an object, the object has to have been created first. Move your creation of the car object to the top of the program.
...
Car carSample = new Car(); // Creates object of class Car
...
carSample.name = input.nextLine();
...
carSample.registration = input.nextLine();
...
carSample.numberOfTrips = input.nextLine();
...
carSample.name = input.nextLine();
Finally, when you use numberOfTrips in the for loop, you need to access it with car.numberofTrips.
I moved numberOfTrips and odometerReading into CarTripHistory class. Check it out:
public static void main(String[] args){
Car carSample = new Car();
Scanner input = new Scanner(System.in);
System.out.print("Input name: ");
carSample.name = input.nextLine();
System.out.print("Input registration: ");
carSample.registration = input.nextLine();
System.out.print("Input colour: ");
carSample.colour = input.nextLine();
CarTripHistory carTripHistory = new CarTripHistory();
System.out.print("Input trips: ");
carTripHistory.numberOfTrips = input.nextInt();
carTripHistory.odometerReading = new double[carTripHistory.numberOfTrips];
for (int i = 0; i < carTripHistory.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i + 1) + ": ");
carTripHistory.odometerReading[i] = input.nextInt();
}
carSample.carTripHistory = carTripHistory;
}
class Car {
String name;
String registration;
String colour;
CarTripHistory carTripHistory;
}
class CarTripHistory{
int numberOfTrips;
double[] odometerReading;
}
You need to create the instance of the object, imagine you have to cars a and b.
And you want them to have different properties, each time you call car a = new car() you are creating a new car, with all the attributes null. And then you can use
a.name = input.nextLine();
So with this you are giving the car a a value to the attribute name, and so on...
Although this is not the best way, because you shouldn't use the attributes directly from the car class on the other class. Instead you should create some constructors and set & get methods.
Related
I'm fairly new to programming so I'm currently stuck on figuring out how to make my code work cleaner. As of right now there are some random dummy lines in my code to make sure i dont skip part certain part of the loops. I was wondering if there are any ways to avoid it.
public static void main(String arg[]) {
String CandidateID;
String Name;
String Option1;
int Test1;
int Test2;
String dummy;
Scanner sc = new Scanner(System.in);
ArrayList<TestResult> StudentResults = new ArrayList<TestResult>();
do {
dummy = sc.nextLine();
System.out.println("Enter student data? y/n");
Option1 = sc.nextLine();
if (Option1.equals("y")) {
System.out.println("Enter Candidate ID:");
CandidateID = sc.nextLine();
System.out.println("Enter Name:");
Name = sc.nextLine();
System.out.println("Enter Test 1:");
Test1 = sc.nextInt();
System.out.println("Enter Test 2:");
Test2 = sc.nextInt();
TestResult TestResult = new TestResult(CandidateID, Name, Test1, Test2);
StudentResults.add(TestResult);
}
}
while (!Option1.equals("n"));
If you don't use the value inside the dummy variable, you can just execute sc.nextLine(); without assigning its return value to a variable.
It'll have the same effect, because the function is still being called.
I'm making an inventory program for my class. I have an Item class, Inventory class with an ArrayList, and an Inventory tester class. I want to ask the user how many items they want to add to inventory and then add those items based on their parameters. This is what I have but it isn't working:
import java.util.Scanner;
public class InventoryTester
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Inventory myInventory = new Inventory();
System.out.println("Enter 1 to print all inventory data");
System.out.println("Enter 2 to add items to the inventory");
System.out.println("Enter 3 to ");
System.out.println("Enter 4 to ");
int choice = input.nextInt();
if (choice == 1)
{
myInventory.printAllData();
}
else if (choice == 2)
{
System.out.println("How many items are you adding?");
int numOfItemsToAdd = input.nextInt();
for (int i = 0; i < numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i);
input.nextLine();
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}
}
input.close();
}
}
EDIT: What I thought my problem was, wasn't actually my problem. I got this piece working.
If you are using nextInt() and nextLine() together, you need to consume the last new line character before calling nextLine(). So you need to add an extra .nextLine() before your for loop like so:
int numOfItemsToAdd = input.nextInt();
input.nextLine(); //ADDED CODE
for (int i = 0; i <= numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i + 1);
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i + 1);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i + 1);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}
i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}
Scanner one = new Scanner(System.in);
System.out.print("Enter Name: ");
name = one.nextLine();
System.out.print("Enter Date of Birth: ");
dateofbirth = one.nextLine();
System.out.print("Enter Address: ");
address = one.nextLine();
System.out.print("Enter Gender: ");
gender = //not sure what to do now
Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.
You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
System.out.print("Enter Gender ('male' or 'female'): ");
gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
do {
System.out.print("Enter Gender (M/F): ");
gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));
You can add an if check after gender assignment to display a invalid message
One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
String str = one.nextLine();
switch (str.toUpperCase()){
case "MALE":
System.out.println("Cool");
break here;
case "FEMALE":
System.out.println("Nice");
break here;
default:
System.out.println("Genders variants: Male/Female");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = readValue(scanner, null);
System.out.print("Enter Date of Birth: ");
String dateofbirth = readValue(scanner, null);
System.out.print("Enter Address: ");
String address = readValue(scanner, null);
System.out.print("Enter Gender: ");
String gender = readValue(scanner, createGenderMatcher());
}
private static IMatcher createGenderMatcher() {
return new IMatcher() {
#Override
public boolean isMatch(String value) {
return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
}
};
}
private static String readValue(Scanner scanner, IMatcher matcher) {
String value = null;
do {
value = scanner.nextLine();
} while (matcher != null && !matcher.isMatch(value));
return value;
}
private interface IMatcher {
public boolean isMatch(String value);
}
Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}