I was trying to implement a java program to process user input from command line.The problem was one given in Algorithms book (sedgewick)
1.1.21 Write a program that reads in lines from standard input with each line contain- ing a name and two integers and then uses printf()
to print a table with a column of the names, the integers, and the
result of dividing the first by the second, accurate to three decimal
places. You could use a program like this to tabulate batting averages
for baseball players or grades for students.
I tried to implement this as follows..but I am stuck in storing the user input sothat it can be printed using printf() ..I thought Scanner would be appropriate for getting the user input..Still I can't seem to get the input stored for later use.
The class Stack is from sedgewick's book.
Any idea how to get this right?
Scanner input = new Scanner(System.in);
Stack st = new Stack();
while(input.hasNext()){
String tkn = input.next();
st.push(tkn);
if (st.size()==3){
int y = Integer.parseInt((String)st.pop());
int x = Integer.parseInt((String)st.pop());
String name = (String)st.pop();
System.out.println("name="+name+",x="+x+",y="+y);
}
}
By using the st.pop() it will remove and return the last item of the stack. If you dont want it to get removed you can use one ordered Collection like ArrayList and access the item by list.get or using an Iterator.
Another suggestion is to create one object to store the name and the y, x properties:
class MyObject {
private String name;
private int x;
private int y;
//... setter and getter methods for the properties
}
Suggestion for your code: it pushes the input in the Stack, then pop the items to create the MyObject and add to the list:
ArrayList listObjects = new ArrayList();
Scanner input = new Scanner(System.in);
Stack st = new Stack();
while(input.hasNext()){
String tkn = input.next();
st.push(tkn);
if (st.size()==3){
int y = Integer.parseInt((String)st.pop());
int x = Integer.parseInt((String)st.pop());
String name = (String)st.pop();
//create and add the object to the list for further use
listObjects.add(new MyObject(name, x, y));
System.out.println("name="+name+",x="+x+",y="+y);
}
}
Related
I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}
I am trying to generate an arraylist in java by first inputting the default size desired of the said arraylist. Then I want to get the user to input the string to fill the arraylist. I have made one that almost works. The only problem is that for some reason I get a default value at the start.
For example, if I set the list length to 3 the list returned is: [,example,value,here]. I understand a value of 3 means 4 values in a list but I feel like that just doesn't look too nice. The problem I think lies in the way I set the size of the list but I don't see any other way.
When I set the list value manually in the for loop I don't get this problem. It only happens when I want the user to input the length. Where is the small error?
import java.util.*;
public class ListsPractice {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
System.out.println("Enter length of desired list: ");
int lenlist = userin.nextInt();
ArrayList list1 = new ArrayList();
for(int counter = 0; counter <= lenlist; counter++) {
System.out.println("Enter an element: ");
String value=userin.nextLine();
list1.add(value);
}
System.out.println("the result is: "+list1.subList(1, lenlist+1));
}
}
today I need some help with adding 4 user defined string, 2 int and 4 double variables into an arraylist as one single index.
Eg: (I'll cut down some of the variables for you, and keep in mind that sc is my scanner object and test results are out of 100)
System.out.print("enter your name")
String name = sc.next();
System.out.print("enter your test results")
double results = sc.nextDouble();
System.out.print("enter your mobile number")
int mobile_num = sc.nextInt(); //I may change this to a string
Now from here, I want to capture these inputs and store them in the array under the number 1 or the user's name. I also want to know how to use this same array to store unlimited inputs from the user through the code mentioned above.
Thanks in advance!
Create your own class UserInput which keeps 10 fields and then generalise a List with this type:
List<UserInput> list = new ArrayList<>();
list.add(new UserInput(name, results, mobile_num, ...));
If you want to associate a user's name with his corresponding input, you had better consider a Map<String, UserInput>:
Map<String, UserInput> map = new HashMap<>();
map.put(name, new UserInput(results, mobile_num, ...));
I have two different programs, one which contains a method "addGrade" designed to add a new grade to a 2D array (gradeTable). One array of the 2D array is the category each grade should be in, and the second element is the grades for each category. Here is that program:
public class GradeBook {
private String name;
private char[] categoryCodes;
private String[] categories;
private double[] categoryWeights;
private double[][] gradeTable;
public GradeBook(String nameIn, char[] categoryCodesIn,
String[] categoriesIn, double[] categoryWeightsIn) {
name = nameIn;
categoryCodes = categoryCodesIn;
categories = categoriesIn;
categoryWeights = categoryWeightsIn;
gradeTable = new double[5][0];
}
public boolean addGrade(String newGradeIn) {
char row = newGradeIn.charAt(0);
int grade = Integer.parseInt(newGradeIn.substring(1));
double[] oldArr = gradeTable[row];
double[] newArr = Arrays.copyOf(oldArr, oldArr.length + 1);
newArr[newArr.length - 1] = grade;
gradeTable[row] = newArr;
return row != 0;
}
The second program reads in a file as a command argument. The bolded text represents the grades being read in. The letter stands for that category each grade should be in, and the number is the actual grade. The file is
Student1
5
a Activities 0.05
q Quizzes 0.10
p Projects 0.25
e Exams 0.30
f Final 0.30
**a100 a95 a100 a100 a100
q90 q80 q100 q80 q80 r90
p100 p95 p100 p85 p100
e77.5 e88
f92**
In the second program, I'm trying to loop through each grade in the file and call the addGrade method on it so it will be added to the 2D array. I'm unsure of how to call the method for each individual grade. Also, I'm pretty sure my addGrade method isn't right. Any help would be appreciated. This is the second program:
public class GradeBookApp {
String fileName = "";
String name = "";
char[] categoryCodes = new char[5];
String[] categories = new String[5];
double[] categoryWeights = new double[5];
double[][] gradeTable;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
System.out.println("Reading file \"" + args[i] + "\"."
+ "\n\tCreating GradeBook object."
+ "\n\tAdding grades to GradeBook object."
+ "\nProcessing of file complete.");
fileName = args[i];
Scanner scanFile = new Scanner(new File(fileName));
name = scanFile.nextLine();
int catCodes = Integer.parseInt(scanFile.nextLine());
for (i = 0; i < catCodes; i++) {
String[] all = scanFile.nextLine().split(" ");
if(all.length == 3 && all[0].length() == 1 && all[2].matches("(\\d+\\.\\d+)")){
categoryCodes[i] = all[0].charAt(0);
categories[i] = all[1];
categoryWeights[i] = Double.parseDouble(all[2]);
}
}
GradeBook myGB = new GradeBook (name, categoryCodes,
categories, categoryWeights);
You'd be better off with having each list of grades as an ArrayList<Double> rather than a double[]. It's very hard work on the JVM (and on the programmer!) having to copy the whole array each time so that you can increase its length and add a new one. If you use an ArrayList<Double> gradeList, then you can just
gradeList.add(grade);
without needing to do all the copying.
I would also consider having the larger structure as a Map rather than an array. So rather than having a two-dimensional array, you could have a HashMap<Character,List<Double>> that maps the row onto the list of grades for that row. That avoids having to convert between characters and doubles, which you're currently (implicitly) doing.
Finally, the addGrade() method ought to take a char and a double (a row and a new grade), rather than a String: you're making a lot of work for yourself with having to process inappropriate data structures.
Once you've done this, calling addGrade for each item should be fairly easy. Once you've extracted a String representing a particular grade (say, String gr = "e77.5") then you can add to the list inside your HashMap gradeMap like this:
char row = gr.charAt(0);
double grade = Double.parseDouble(gr.substring(1));
gradeMap.get(row).add(grade);
I think you'll need to supply more info if you need more help than that.
You stated that you need to read from a file, but none of your code is actually reading from a file. This should be your first step. Try looking at BufferedReader documentation as well as numerous posts on this site regarding proper methods to perform file IO operations.
I'm assuming your storing your grades in the 2D gradeTable array like: {Category, grade}. You will need to read each row in your file(BufferedReader has methods for this), parse the string (Look at the String documentation, specifically split or substring/indexOf methods) into category and grade, and then populate your array.
Look into using more dynamic data structures, such as ArrayList. This will allow you to expand the size as you add more grades, as well as not having to copy your array into a new array every time the size expands.
I'm working on a program that acts as a type of book store inventory. The program reads in a list of information from a text file that looks like this:
1234567 31.67 0
1234444 98.50 4
1235555 27.89 2
1235566 102.39 6
1240000 75.65 4
1247761 19.95 12
1248898 155.91 0
1356114 6.95 17
1698304 45.95 3
281982X 31.90 5
The first number represents the ISBN number and is the type String, the second number is the price and is type double, and the final number is the number of copies in stock and is an int.
The program is supposed to read in this information, storing it into an array (more steps follow, but this is the first thing I'm having trouble with).
The code I have so far looks like this:
import java.util.Scanner;
import java.io.*;
public class Store {
public static void main(String[] args) {
String[] books = new String[15];
String product;
readInventory();
}
public static void readInventory() {
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
String isbn;
double price;
int copies;
String[] books = new String[14];
while (fin.hasNext()) {
isbn = fin.next();
price = fin.nextDouble();
copies = fin.nextInt();
}
}
}
I'm having trouble figuring out how to store these three different pieces of information into a single line (for each item like is depicted in the file) in a single dimensional array.
One thought I had was to created something like this,
String product = (isbn + price + copies);
And then try to add this to the array like,
String[] books = product;
But as I'm sure you can probably sport, this didn't work. Any suggestions would be greatly appreciated. I'm still really new to this and it's been a while since I've worked with arrays.
I'm having trouble figuring out how to store these three different pieces
of information into a single line
How about using nextLine()
String[] books = new String[14];
int index = 0;
while (fin.hasNextLine()) {
books[index] = fin.nextLine();
index++;
}
From there you can pull out each String and split it around the spaces
String[] parts = books[0].split(" ");
Now you can cast each part to its respective type
String isbn = parts[0];
double price = Double.parseDouble(parts[1]);
int numberInStock = Integer.parseInt(parts[2]);
Beware this is a long way around and will cause problems if your file contains variable amounts of books. Also, to do this for all books will require some loops.