Okay so i created this program which is unfinished that allows you to insert a students name and test score into a string. But my probably is, im trying to use if statements so that the user is able to type in a number and choose what they wish to do.
Im trying to have it so after the user has inserted the name and test score, they can choose to have the name and test score printed out, or they can quit or insert another name but i cant because the string is not set globally.
does anyone know how to do this? Thank You,
package week14;
import java.util.Scanner;
public class Task4 {
private static Scanner input;
private static Scanner input2;
public static void main (String [] args){
input2 = new Scanner (System.in);
System.out.println("Student Mark Program");
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Student name and mark");
System.out.println("2. Quit");
int choice = input2.nextInt();
System.out.println();
if (choice == 1){
opt1();
}
else if (choice == 2){
quit();
}
}
public static void opt1(){
input = new Scanner(System.in);
String firstname;
String surname;
int score1;
System.out.print("Enter the students first name: ");
firstname = input.next();
System.out.print("Enter the students surname: ");
surname = input.next();
String full_name;
full_name = firstname + " " + surname;
System.out.println("Please enter students score: ");
score1 = input.nextInt();
System.out.println("Name : " + full_name);
System.out.println("Score: " + score1);
System.out.println();
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Another Student name");
System.out.println("2. Get student name");
System.out.println("3. Get student name and mark");
System.out.println("4. Quit");
int choice = input.nextInt();
System.out.println();
if (choice == 1){
opt6();
}
else if (choice == 2){
opt2();
}
else if (choice == 3){
opt3();
}
System.out.println();
input.close();
}
public static void opt2(){
System.out.println("Name : " + full_name);
}
public static void opt3(){
}
public static void opt4(){
}
public static void opt5 (){
}
public static void opt6 (){
}
public static void quit(){
System.out.println("You have quit the program");
System.exit(0);
}
}
Put this static String full_name; under where you declare private static Scanner input2; in your class. Not necessarily good programming practice to use global variables, but for your purposes it will likely get the job done.
Well, I would initialize a new global variable set your full_name to and return it as an accessor method.
public static String getName()
{
return (nameOfString);
}
Also, I see that you want to make an other command to change your name and you could do that with a settor method.
public static void setName(String newName)
{
originalString = newName;
}
Related
i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.
I have created a program in JAVA that has menu Options, 1 to 5. Option 4 being "Add student". Where it asks a 4 questions
Questions:
Please Enter student name:
Please Enter student course:
Please Enter student number:
Please Enter student gender:
After user has given these details, It will save into an array and ends the program. I am quite lost on how to save these details into an array.
This is my program where i tried to find a solution myself, But im relatively new to arrays and method myself.
public static void newstudent (String[] name,String[] course,int[] number,String[] gender)
{
}
public static void selection (int option) // Menu
{
switch (option)
{
case 1:
System.out.println("Display Student option");
break;
case 2:
System.out.println("Search Student");
break;
case 3:
System.out.println("Delete Student");
break;
case 4:
//code for adding new student
break;
case 5:
System.out.println("Exited");
break;
default:JOptionPane.showMessageDialog(null, "Invalid option! Please enter in the range from 1 to 5.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
//Start of Menu loop Statement
int option1 ;
do{
String option = JOptionPane.showInputDialog(null,"Enter your option:\n"+"\n"+"1. Display Students\n"+"2. Search Students\n" + "3. Delete Students\n"+"4. Add Students\n"+"5. Exit ","DMIT Students",JOptionPane.QUESTION_MESSAGE);
option1 = Integer.parseInt(option);
selection(option1);
}while(option1 <1 || option1 > 5);
// End of Menu Loop statement
}
}
i tried doing a for loop to add +1 to these array everytime a user inputs all these details but the for loop will be stuck in a infinite loop. Is there any suggestions that i can get? or easier solutions?
You shouldn't use arrays (the way you are using here) in the first place because you don't want to store the details of single student in four different places i.e. arrays. You can define a class Student with all the details you need and then it will be simple to add the details using class instances. Something like -
public class Student
{
private String m_name;
private int m_age;
private String m_course;
private String m_year;
private String m_section;
public Student( String name, int age, String course, String year, String section )
{
m_name = name;
m_age = age;
m_course = course;
m_year = year;
m_section = section;
}
public String getName()
{
return m_name;
}
public int getAge()
{
return m_age;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public String getSection()
{
return m_section;
}
public String toString()
{
return "name: " + m_name + ", age: " + m_age +
", course: " + m_course + ", year: " + m_year +
", section: " + m_section;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
Student student = new Student(name, age, course, year, section);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
}
} while (menuChoice<4);
}
}
The above code snippet is referred from here.
I am new to Java and have recently started coding within the last week. I have tried to build some basic things and did the following:
import java.util.Scanner;
public class App {
public static void main(String[] args){
// creating scanner object
Scanner userSex = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = userSex.nextLine();
System.out.println("Thank you, you entered " + sex );
// new scanner
Scanner userAge = new Scanner (System.in);
System.out.println("Are you a child or adult: ");
String age = userAge.nextLine();
System.out.println("You are a " + sex + " " + age);
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
}
}
Unfortunately however, only the top of the code runs. The below code doesn't run and doesn't print anything out even when I enter "child" or "adult".
if (userAge.equals("child")) {
System.out.println("children");
} else if (userAge.equals("adult")) {
System.out.println("adults");
}
instead of
if(userAge.equals("child")) {
System.out.println("children");
}
else if(userAge.equals("adult")) {
System.out.println("adults");
}
do this
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
The one thing that was already mentioned is that you only need one scanner object. It's unnecessary to create one for each string entered. The main problem is that you are testing if userAge equals "child" or "adult", but userAge is the scanner object. I think you meant to write age.equals("child"), as age is the actual String entered.
The following works:
import java.util.Scanner;
public class App {
public static void main(String[] args){
//creating scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = in.next();
System.out.println("Thank you, you entered " + sex );
//new scanner
System.out.println("Are you a child or adult: ");
String age = in.next();
System.out.println("You are a " + sex + " " + age);
if(age.equals("child")) {
System.out.println("children");
}
else if(age.equals("adult")) {
System.out.println("adults");
}
}
}
Rather than creating two separate scanners you just use one and call the next()method. I also change the condition from if(userAge... to if(age...
There is no need to create two scanner object .Just create one scanner object.
You can also use BufferedReader instead of Scanner.In your code you use userAge.equals("child") .but this is not right since you store the value returned by scanner in age , use age to compare in if-else codition like age.equals("child")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your sex (male or female): ");
String sex = scanner.nextLine();
System.out.println("Thank you, you entered " + sex );
System.out.println("Are you a child or adult: ");
String age = scanner.nextLine();
System.out.println("You are a " + sex + " " + age);
if (age.equals("child")) {
System.out.println("children");
} else if (age.equals("adult")) {
System.out.println("adults");
}
Reference Link:https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
This is my code. The program won't give me the last print line "Thank you for using the Basic user Interface program."
public class nameClass {
public static void main(String[] args) {
String input;
String name;
int age;
double mileage;
displayApplicationInformation();
displayDivider("Start Program");
TerminateApplication();
// process name
displayDivider("Get Name");
name = getInput("name");
System.out.println("Your name is: " + name);
// Process age
displayDivider("Get Age");
input = getInput("Your age");
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
// Process Mileage
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
}// end of main
public static void displayApplicationInformation()
{
System.out.println("Welcome to the Basic User Interface Program");
}// end of displayApplicaionInformation
public static void displayDivider(String outputTitle) {
System.out.println("*********" + outputTitle + "********");
}// end of displayDvider
public static String getInput(String inputType)
{
String input = "";
input = JOptionPane.showInputDialog("Enter the " + inputType);
return input;
}
public static void TerminateApplication()
{
System.out.println("Thank you for using the Basic User Interface program");
return;
}
}// end of MainClass
You have to actually call the method TerminateApplication;
System.out.println("Your car MPG is: " + mileage);
TerminateApplication();
Simple, call TerminateApplication.
You are doing it on the 9th line of main().
Here, check this out:
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
//add this...
TerminateApplication();
Hope this helps!
im working on a school project.
We have to create a contact list.
So, i created a class generating objects like.
package coursework_q2;
public class Agenda {
private String name;
private long phoneNumber;
private String email;
private String type;
public Agenda(){
name = "";
phoneNumber = 0;
email = "";
type = "";
}//end of constructor
#Override
public String toString() {
return "\nName: " + this.getName() +
", Number: " + this.getPhoneNumber() +
", Email: " + this.getEmail() +
", Type: " + this.getType();
}
//setters
public void setName(String n){
name = n;
}//end of setName
public void setPhoneNumber(long n){
phoneNumber = n;
}//end of setPhoneNumber
public void setEmail(String e){
email = e;
}
public void setType(int t){
if (t==1){
type = "Personal";
}else{
type = "Business";
}
}//end of setType
//getters
public String getName(){
return name;
}//end of getName
public long getPhoneNumber(){
return phoneNumber;
}//end of getPhoneNumber
public String getEmail(){
return email;
}//end of getEmail
public String getType(){
return type;
}//end of getType
}//end of class
And in my other class i store them in an arraylist.
My problem is that i dont know how to create as many contacts as the user wants.
For example:
package testcourse;
import java.util.ArrayList;
import java.util.Scanner;
public class CourseWork_Q2 {
public static void main(String[] args) {
ArrayList<Agenda> contacts = new ArrayList();
Scanner in = new Scanner(System.in);
int check;
String contact;
String search;
Agenda a;
a = new Agenda();
int select=0;
int b=0;
do {
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
System.out.print("Please use the numbers 1-5 to choose an option: ");
do{//input validation
check=0;
if(in.hasNextInt()){
select = in.nextInt();
if(1<=select && 5>=select){
check=1;
}else{
System.out.println("Invalid Input!\nPlease use the numbers 1-5 to choose an option: ");
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
}//end of if
}else{
System.out.println("Invalid Input!\nPlease use the numbers 1-5 to choose an option: ");
System.out.println("1. Add Contact\n2. Edit Contact\n3. Delete Contact\n4. Display All Contacts\n5. Quit");
in.next();
}//end of if
}while(check==0);
switch(select){
case 1: System.out.println("Add Contact");
System.out.print("Please enter your contact name: ");
a.setName(in.next());
System.out.print("\nPlease enter your contact phone-number: ");
a.setPhoneNumber(in.nextLong());
System.out.print("\nPlease enter your contact email: ");
a.setEmail(in.next());
System.out.print("\nPlease choose your contact type: ");
System.out.println("\n1. Personal\n2. Business");
a.setType(in.nextInt());
contacts.add(a);
break;
case 2: System.out.println("Edit Contact");
System.out.println("Please enter the name of the contact you wish to edit: ");
search = in.next();
for(int i=0; i<contacts.size(); i++){
contact = (contacts.get(i)).toString();
if(contact.contains("Name: "+search)){
System.out.println(contacts.get(i));
System.out.println("Please edit the name");
a.setName(in.next());
}
}
break;
case 3: System.out.println("Delete Contact");
break;
case 4: System.out.println("Display All Contact");
for (int i=0; i<contacts.size(); i++){
System.out.println(contacts.get(i));
}
break;
case 5:
System.exit(5);
break;
}//end of switch
}while (!(check==5));
}//end of main
}//end of class
and so on..
How i can do this automatically with my code? So the user can create as many contacts as he wants?
Thank you!
Create an ArrayList of Agendas:
ArrayList<Agenda> contacts = new ArrayList<Agenda>();
Every time you want to add a contact, create a new Agenda, set the values, and add it to the ArrayList
Agenda a = new Agenda();
// Do stuff to the agenda/contact, like set names and stuff
contacts.add(a); // Adds the agenda/contact to the ArrayList
To edit a contact, all you need to do is retrieve it from the ArrayList with the index of it in the array.
int index = 1; // Set it to whichever you need
Agenda a = contacts.get(index);
// Now change whatever is in the agenda
To remove a contact, just remove it from the ArrayList using the index.
int index = 5;
contacts.remove(index);