I want to implement a two-dimensional array using user input. I have a Book class. It has two variables: int price and String name. I want to store 5 books information in a two-dimensional array. Book class code is below:
public class Book {
String name;
int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
Main Class code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int l = 5;
Book[][] bk = new Book[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
// here i want to take user input.
System.out.println("Enter Song: ");
String sname = in.next();
System.out.println("Enter price: ");
int sprice = in.nextInt();
// in this line i am getting type
// error int can't convert to string
song[i][j] = song[sname][price];
}
}
}
You never declared the array song, maybe you wanted to write
bk[i][j] = ...
Now you want to create a new "Book" for every sname and sprice that you read, so you have two options:
1) In each iteration create a new empty Book
Book tmp = new Book();
then you set his Name and his Price
tmp.setName(sname);
tmp.setPrice(sprice);
and then you assign the new Book to the current element of bk
bk[i][j] = tmp;
or
2) Add a constructor to the class Book that has Name and Price as parameters
public Book(String n, int p){
name = n;
price = p;
}
and use it to instantly create a new Book and assign it to the current element of bk
bk[i][j] = new Book(sname, sprice);
So what you require is Book[String name][int price]. That is not how 2D arrays work.
While declaring:
int l = 5;
Book[][] bk = new Book[l][l];
You are implementing a 2D Book array that can have 25 book records.
1D array of Books is sufficient for your requirements.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int l = 25;//any size you can have
Book[] bk = new Book[l];
for (int i = 0; i < l; i++) {
System.out.println("Enter Song: ");
String sname = in.next();
System.out.println("Enter price: ");
int sprice = in.nextInt();
Book book = new Book();
book.setName(sname);
book.setprice(sprice);
bk[i] = book;
}
}
Related
I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}
When I try to use scanner on another class I can't update the array.
private int numClients;
private int[] clients;
These are variables from my class Rooms.
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients = new int[numClients];
}
Of course I added setters and getters:
public String getName() {
return name;
}
public void setNaziv(String name) {
this.name = name;
}
public int getNumRooms() {
return numRooms;
}
public void setNumRooms(int numRooms) {
this.numRooms = numRooms;
}
public int getNumClients() {
return numClients;
}
public void setNumClients(int numClients) {
this.numClients = numClients;
}
When I tried to add it to test it in another class, name and numRooms change. numClients change too but array doesn't update.
Hotel h1 = new Hotel(" ", 0, 0);
String name= sc.nextLine();
h1.setName(name);
int numRooms= sc.nextInt();
h1.setNumRooms(numRooms);
int numClients= sc.nextInt();
h1.numClients(numClients);
h1.show();
This is the show method:
public void show(){
System.out.println("Name: " + this.name);
System.out.println("Rooms: " + this.numRooms);
System.out.println("Number of clients: " + this.numClients);
for(int i = 0; i < clients.length; i++) {
System.out.println(clients[i]);
}
}
Maybe there will be some typing errors I translated the var names to English for question purposes.
Once you have created the array, it's size is fixed. You can test this with a few rows:
int size = 10; // Start with size 10
int[] array = new int[size]; // Array is 10 elements long
System.out.println(size); // Prints 10
System.out.println(array.length); // Also prints 10
size = 1000; // Change size ??
System.out.println(size); // Prints 1000
System.out.println(array.length); // Still prints 10
Output:
10
10
1000
10
You also don't appear to actually set any elements in the array in your code. That would be something like
h1.getClients()[0] = 3;
Edit
When this line in your constructor is exectuted:
this.clients = new int[numClients];
The array is created with the size that numClients has right at that moment. After that, there is no relation between numClients and clients anymore.
You would need to create a new array, copy contents (if you want to preserve it) and reassign clients with the new array in order to change the size.
You can do this with Arrays.copyOf() :
int newLength = 20;
array = Arrays.copyOf(array, newLength);
System.out.println(array.length); // Prints 20!!
The constructor will run once for a single object. So, if you want to add more values in the clients array then a method is a must.
The main Class:
class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel("romeo",5,10);
hotel.addClients(6);
hotel.addClients(10);
hotel.addClients(5);
hotel.show();
}
}
The Hotel Class:
class Hotel{
private int numRooms,numClients;
private String name;
private int clients[] = new int[10];
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients[0] = numClients;
}
The method to add Clients in the clients array:
public void addClients(int numClients){
for(int i = 0; i < clients.length; i++){
if(clients[i] == 0){
clients[i] = numClients;
break;
}
}
}
Show method output:
Name: romeo
Rooms: 5
Number of clients: 10
10
6
10
5
The Total number of clients can be found by summation of the clients array.
To make the array dynamic, the linked list data structure can be applied.
What I did to fix this without updating and making new methods is defining values with scanner and putting it into constructor.
public void test(){
Scanner sc = new Scanner(System.in);
System.out.print("Type in the name of Hotel: ");
String name= sc.nextLine();
System.out.print("Type in number of rooms: ");
int numRooms = sc.nextInt();
System.out.print("Type in the number of clients");
int numClients= sc.nextInt();
Hotel h1 = new Hotel(name, numRooms, numClients);
h1.show();
}
The code is to sort the and print students name according to their marks in descending order. In a class there are ‘n’ number of students. They have three different subjects: Data Structures, Algorithm Design & Analysis and Operating Systems. Marks for each subject of all the students are provided to you. You have to tell the position of each student in the class. Print the names of each student according to their position in class. Tie is broken on the basis of their roll numbers. Between two students having same marks, the one with less roll number will have higher rank. The input is provided in order of roll number.
I am able to implement the code in which I made a pair class to sort according to their marks and stored all the object in the array. After that I used Array.sort to sort the array.
So how did the Arrays.sort(pair) sorted the array on what basis.
import java.util.*;
public class Main{
static class pair implements Comparable<pair>{
int marks;
String name;
public pair(int m, String n){
this.marks = m;
this.name = n;
}
#Override
public int compareTo(pair p){
return p.marks - this.marks;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
// String sn = in.nextLine();
int n = in.nextInt();
pair[] arr= new pair[n];
for(int i =0;i< n;i++){
String name = in.next();
int sum = 0;
for(int j = 0;j<3;j++){
int num = in.nextInt();
sum += num;
}
int marks = sum ;
arr[i]= new pair(marks,name);
}
Arrays.sort(arr);
for(int i = 0;i<arr.length;i++){
System.out.println(i+1 +" "+arr[i].name);
}
}
}
In the below code comparator is doing compare on basis of marks. Array.sort uses a customized comparator.
package stackoverflow;
import java.util.Arrays;
import java.util.Comparator;
class Student {
int rollno, marks;
String name;
public Student(int rollno, int marks, String name) {
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
public String toString() {
return this.rollno + " " + this.name + " " + this.marks;
}
}
class Sortbymarks implements Comparator<Student> {
public int compare(Student a, Student b) {
return b.marks - a.marks;
}
}
public class ArraySort {
public static void main(String[] args) {
Student[] arr = { new Student(111, 150, "abc"), new Student(131, 100, "abcd"), new Student(121, 120, "xyz"),
new Student(191, 150, "txy") };
System.out.println("Unsorted");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
Arrays.sort(arr, new Sortbymarks());
System.out.println("Sorted by marks");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
Here is my answer. I want to know how Arrays.sort() sorts the object pair after it has already been sorted according to their marks.
import java.util.*;
public class Main{
static class pair implements Comparable<pair>{
int marks;
String name;
public pair(int m, String n){
this.marks = m;
this.name = n;
}
#Override
public int compareTo(pair p){
return p.marks - this.marks;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
// String sn = in.nextLine();
int n = in.nextInt();
pair[] arr= new pair[n];
for(int i =0;i< n;i++){
String name = in.next();
int sum = 0;
for(int j = 0;j<3;j++){
int num = in.nextInt();
sum += num;
}
int marks = sum ;
arr[i]= new pair(marks,name);
}
Arrays.sort(arr);
for(int i = 0;i<arr.length;i++){
System.out.println(i+1 +" "+arr[i].name);
}
}
}
I cannot figure out how to format the code for my if-statements. Typically, I would take a string input from the user and use .equals, however the object I am required to use makes that impossible. Whenever I print the contents of the array, I get references. I want to get a user input stored to be stored in the array and printed in a later line of code.
Question: If possible, how do I get a scanner input to be assigned to a "Team" and referenced for comparison in the if-statements? How should I go about assigning these values?
Here is the code I was given
public class Team implements Comparable<Team> {
public String toString(String team, int wins) {
String winningStatement = team + ": " + wins;
return winningStatement;
}
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
Here is my attempt at using an ArrayList
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
Thank you for the assistance
Judging only by the intent of your example... it appears that this is what you are trying to achieve. As stated though, your question of how ArrayList objects relate to overloaded constructors does not really make sense
public class Team {
// Data fields
private String name;
private int winCount;
public Team() {
name = "Sooners";
winCount = 1;
}
public Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
public String toString(String team, int wins) {
return team + ": " + wins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinCount() {
return winCount;
}
public void setWinCount(int winCount) {
this.winCount = winCount;
}
void incrementWinCount() {
winCount++;
}
}
void runSystem() {
List<Team> teams = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int cycles = 0;
System.out.println("Welcome to the Advanced Sportsball Tracker!");
System.out.println("Which team just won? (x to exit)");
String name = scnr.next();
while (!"x".equals(name)) {
final String teamName = name;
Team team = teams.stream().filter(t -> teamName.equals(t.getName())).findAny().orElse(null);
if (team == null) {
team = new Team(teamName, 1);
teams.add(team);
}
else {
team.incrementWinCount();
}
cycles++;
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
}
}
I have created a class called Employee and i have set the variable for it. Now im creating an object for that class. In this object i want to create a function called "GetValue" and it should initialize the variables i have created in the class Employee. I want it to get e.g employee name, employe number etc. I have start some coding but im stuck on this..
//main class
public class Employee {
//variable declaration
private String EName, EDesig;
private double BSal=0.0, HA=0.0, GSal=0.0;
private int EmpNo;
// constructor;
public void Employee (String EnNameParameter, String EDesigParameter, double BSalParameter, double HAParameter, double GSalParameter, int EmpNoParameter)
{
this.EName = EnNameParameter;
this.EDesig = EDesigParameter;
this.BSal = BSalParameter;
this.HA = HAParameter;
this.GSal = GSalParameter;
this.EmpNo = EmpNoParameter;
} // End constructor;
// Get methods;
public String getEName(){
return this.EName;
}
public String getEDesig(){
return this.EDesig;
}
public double getBSal(){
return this.BSal;
}
public double getHA(){
return this.HA;
}
public double getGSal(){
return this.GSal;
}
public int getEmpNo(){
return this.EmpNo;
}
//Set methods;
public void setEName(String Ename){
this.EName = EName;
}
public void setEDesig(String EDesig){
this.EDesig = EDesig;
}
public void setBSal(double BSal){
this.BSal = 0.0;
}
public void setHA(double HA){
this.HA = 0.0;
}
public void setGSal(double GSal){
this.GSal = 0.0;
}
public void setEmpNo(int EmpNo){
this.EmpNo = EmpNo;
}
}
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// create object
Employee a = new Employee();
Employee b = new Employee();
Employee c = new Employee();
Scanner input = new Scanner (System.in);
System.out.println("Enter The Number of Employee");
int number = input.nextInt();
int[] N = new int[3]; // instanitate array
int i;
for(i=0; i<number; i++){
}
getValues();
CalculateSalary();
DisplayValues();
}
}
Something like this?
// make an empty list
List<Employee> employees = new ArrayList<>();
// make a scanner that reads from stdin
Scanner sc = new Scanner(System.in);
System.out.print("How much employees does your company have?");
int n = sc.nextInt() // nr of employees
for(int i = 0; i < n; i++) { // loop over all employees
// read the information of the ith employee
System.out.print("What is the name of the i th employee?");
String name = sc.next();
int age = sc.nextInt()
// make an employee object
Employee employee = new Employee(name, age);
employees.add(employee); // add the employee to the list
}
// Now you have a list with n employees
// to print all employees on stdout
for(Employee e : employees) {
System.out.println(e.toString());
// make a toString() method in you Employee class,
// else this will not work properly
}
How about creating an object array to the number input by the user. The following code will help you:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Enter The Number of Employee");
int number = input.nextInt();
Employee[] emp = new Employee[number]; // create object array for no of employees
for(int i=0; i<number; i++){
emp[i].setBSal(100);
emp[i].setEDesig(null);
emp[i].setEName("Ann");
emp[i].setEmpNo(234);
emp[i].setGSal(34);
}
getValues();
CalculateSalary();
DisplayValues();
}
This is the main class. You can either use user inputs to set each method.