I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY#foo.com
The output:
NAME: Happy
EMAIL: HAPPY#foo.com
I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
import java.util.ArrayList;
import java.util.Scanner;
public class Program5 {
void loadContacts()
{
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
scan.close();
}
void printContacts()
{
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
}
Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
private String name;
private String mail;
public Program5(){}
void loadContacts(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a name and a mail like this : name email#email.com (separate with ' ')");
String[] line = scan.nextLine().split(" ");
while(line.length!=2){
System.out.println("Again, enter a name and a mail like this : name email#email.com (separate with ' ')");
line = scan.nextLine().split("/");
}
this.setName(line[0]);
this.setMail(line[1]);
scan.close();
}
void printContacts() {
System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
}
public static void main(String[] args) {
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
public void setName(String name) {
this.name = name;
}
public void setMail(String mail) {
this.mail = mail;
}
}
In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)
You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;
The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String arr[] = input.split("\\s+");
Name = arr[0];
Email = arr[1];
scan.close();
}
And finally on void printContacts().
void printContacts()
{
System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}
Here is the code runnig: http://ideone.com/mjyfHK
You can do a variety of things.
You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.
or
You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.
Related
So I am using eclipse to practice coding using java and till now it was doing great, until I wrote this program:
import java.util.*;
public class cars {
String name;
int dom;
Scanner in = new Scanner(System.in);
void takedata()
{
name=in.next();
dom=in.nextInt();
}
void displaydata()
{
System.out.print("Enter the name of the car"+name);
System.out.print("Enter the Date of Manufacture of the car"+dom);
}
public static void main(String[] args)
{
cars x = new cars();
cars y = new cars();
cars z = new cars();
x.takedata();
y.takedata();
z.takedata();
x.displaydata();
y.displaydata();
z.displaydata();
}
}
whenever I am trying to run the code it is showing me nothing.
I need help.
It wont show anything. Your code will wait till you enter the care name. So, first you need to provide input as your takeData() method is getting called before displayData(). Modify your takeData() method as shown below:
void takedata()
{
System.out.println("Enter Name of the Car: ");
name=in.next();
System.out.println("Enter Date of Manufacture: ");
dom=in.nextInt();
}
Then after executing your program your will be able to see below message:
Enter Name of the Car:
I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.
I want to create a code that allows you to put in a word then it searches through the Arraylist, then it sends that code with the new airport codes. I can't figure out how to search through the ArrayList and then print certain letters. One of my friend suggested HashMap, but it only wants me to put in integers for the letters.
import java.util.*;
public class Alphabet {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Put in a word, the machine will then translate it to airport codes!");
String name = in.next();
List<String> name1 = new ArrayList<String>();
name1.add("Alpha");
name1.add("Bravo");
name1.add("Charlie");
name1.add("Delta");
name1.add("Echo");
name1.add("Foxtrot");
name1.add("Golf");
name1.add("Hotel");
name1.add("India");
name1.add("Juliet");
name1.add("Kilo");
name1.add("Lima");
name1.add("Mike");
name1.add("November");
name1.add("Oscar");
name1.add("Papa");
name1.add("Quebec");
name1.add("Romeo");
name1.add("Sierra");
name1.add("Tango");
name1.add("Uniform");
name1.add("Victor");
name1.add("Whiskey");
name1.add("X-Ray");
name1.add("Yankee");
name1.add("Zulu");
for (String string : name1) {
if(name.equals(name1)){
name1.equals(name1);
}
}
System.out.println(name1);
}
}
That was a simple mistake, you are iterating the list but you did not take the string value to check with your name
for (String string: name1) {
if(name.equals(string)){
//Your code
}
}
You can use the following code as well.
name1.forEach(string -> {
if (string.equals(name)) {
System.out.println("found");
} else System.out.println("Not found");
});
public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());
I'm currently working on a project for class but struggling with a bit of coding relating to
ArrayLists. It is as yet unfinished code; however, when I'm working on the enrollstudent
method I'm having an issue comparing the length of an ArrayList to the variable amountstudents.
Below is a copy of the code for the full class. There is another seperate class related but I don't think it's relevant here.
Any help would be greatly appreciated.
import java.util.*;
import java.util.Scanner;
public class Course {
int amountstudents;
String coursename;
String level;
ArrayList<String> students = new ArrayList<String>();
String tutor;
Scanner in = new Scanner(System.in);
public Course(int MaxCapacity) {
MaxCapacity = amountstudents;
tutor = "Not set yet";
coursename = "Not set yet";
level = "Not set yet";
}
public void enrollstudent(String addstudent) {
if(students.size > amountstudents) {
System.out.println("Unfortunately the class is already full so you can not be enrolled at this time");
}
else {
students.add(Student.fname);
}
}
public void courselevel() {
System.out.println("Please enter course level");
level=in.next();
}
public void coursetitle() {
}
}
It's students.size(), not students.size.
Also, there's another error:
It should be students.add(addstudent), not students.add(Student.fname).
It's students.size(), since students is an ArrayList
You want to use students.size(). size is a method on List types, not a property (like length is on arrays).
Also, in the constructor, you have this reversed:
MaxCapacity = amountstudents;
it should be:
amountstudents = MaxCapacity;