How to avoid using the dummy lines? - java

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.

Related

Assign multiple values of objects using a loop

The question requires us to create two objects of the Student class and have 5 variables. The variables will be assigned a value each through user input.
Is there a way to use a loop or anything else to take the user inputs from there instead of writing each variable individually using the dot operator?
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student();
Student student2 = new Student();
//Input for student 1
student1.name = input.nextLine();
student1.gender = input.next().charAt(0);
student1.cgpa = input.nextDouble();
student1.roll[0] = input.nextInt();
student1.age = input.nextInt();
//Input for student 2
student2.name = input.nextLine();
student2.gender = input.next().charAt(0);
student2.cgpa = input.nextDouble();
student2.roll[0] = input.nextInt();
student2.age = input.nextInt();
}
}
class Student {
String name;
char gender;
double cgpa;
int[] roll;
int age;
}
We can create a constructor for the class Student that takes in the parameters and defines them as so:
class Student {
String name;
char gender;
double cgpa;
int[] roll = new int[10];
int age;
public Student(String n,char g,double c,int r,int a){
name = n;
gender = g;
cgpa = c;
roll[0] = r;
age = a;
}
public String toString(){
return name;
}
}
Note that we must give roll a specified length before assigning it any elements. Alternatively, we could use an ArrayList instead of an array for roll if we are not given the length (I used 10 as a placeholder).
As for the main method, we can now define student1 and student2 in one line each:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
input.nextLine();
Student student2 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
System.out.println(student1);
System.out.println(student2);
}
}
Notice how between the declarations of student1 and student2 there is a input.nextLine(). This is because after we take the final parameter, an integer, for student1, the input will leave a trailing newline which will mess with the user input for student2. To fix this, we can scan the line to get rid of the whitespace.
I hope this helped! Please let me know if you need any further clarification or details :)

Placing object variables in scanner

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.

ReplaceAll with string builder with user input

I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little

Can someone help me figure out why one of my methods is not running at all?

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

I need to create a program that will add, remove, list, save, and sort students in a created Student, Undergrad, and Graduate classes

I have three different classes, one for grad students, undergrads, and then a general student class, I need to figure out how to add students to an array list, from the main method. I can't figure out how to add a first name because it is private, and it needs to stay private.
package enrollmentdatabase;
import java.util.ArrayList;
import java.util.Scanner;
public class EnrollmentDataBase {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String option = optionChoise(input);
String option1 = "ADD";//ADD option
String option2 = "REMOVE";//REMOVE OPTION
String option3 = "LIST";//LIST OPTION
String option4 = "SAVE";//SAVE OPTION
String option5 = "SORT";//SORT OPTION
ArrayList studentList = new ArrayList();
}//end of main method
public static String optionChoise(Scanner input){
String opt1 = "ADD";//ADD option
String opt2 = "REMOVE";//REMOVE OPTION
String opt3 = "LIST";//LIST OPTION
String opt4 = "SAVE";//SAVE OPTION
String opt5 = "SORT";//SORT OPTION
System.out.println("Enter what you want to do(ADD, REMOVE, LIST, SAVE, or SORT): ");
String opt = input.nextLine();
if((opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) != 0 || (opt.compareToIgnoreCase(opt1)) !=0
|| (opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) !=0){//enter this if conditional in order to establish that the input is valid
System.out.println("This is not a valid input, please enter in what you want to do: ");
opt = input.nextLine();
}//end of if conditional
return opt;
}//end of option method
public static ArrayList addList(ArrayList studentList, Scanner input){
System.out.println("Enter the Student's first name: ");
String nameFirst= input.nextLine();
Student student1 = new Student();
student1.firstName = nameFirst;
System.out.println("Enter the Student's last name: ");
System.out.println("Enter the Student's UID: ");
System.out.println("Enter the Student's status: ");
System.out.println("Enter YES for having a thesis option, else NO: ");
System.out.println("Enter Masters for Master Studies of PHD for PHD studies: ");
System.out.println("Enter the name of the major professor: ");
System.out.println("Enter the student class standing: ");
System.out.println("Enter the Student's major: ");
System.out.println("Enter the student's overall GPA: ");
System.out.println("Enter the student's major GPA: ");
}//end of addList method
}//end of class
I can't figure out how to add a first name because it is private,
have public getter and public setter methods for that private data and access it through them.
For instance:
class Student {
private String fName;
public void setFname(String fName){
this.fName = fName;
}
public String getFName(){
return fname;
}
}
class AnotherClass {
public static void main(String...args){
student s = new Student();
System.out.println(s.getFName());//to access fName(which is private) in class Student.
}
}

Categories

Resources