i am in desperate need of more help this week. My professor is sub par and makes no effort to clear things up.
The Problem:
import a file and search for a specific piece of data that is requested by a user.
The output must return something similar to:
Sequential found ID number 77470, and its price is $49.55.
or
Sequential did not find ID number 77777.
I have no idea where to go from here, or even if this is correct....
public class MainClass
{
public static void main(String[] args)
{
Payroll acmePay = new Payroll();
Scanner myScanner = new Scanner(System.in);
int target;
acmePay.loadEmpNums();
System.out.println("Enter the product number you would like to search: ");
target = myScanner.nextInt();
System.out.print(acmePay.seqSearch(target));
myScanner.close();
}//END main
}//END class MainClass
Payroll Class:
public class Payroll
{
private int[] empNums = new int[1000];
private int empCount = 0;
Payroll(){} //Currently nothing done in constructor
public void loadEmpNums()
{
String name;
double salary;
empCount = 0; //Just to make sure!
try
{
String filename = "employees.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNext())
{
//Read a complete record
empNums[empCount] = infile.nextInt();
name = infile.nextLine();
salary = infile.nextDouble();
//Increment the count of elements
++empCount;
}
infile.close();
}
catch (IOException ex)
{
//If file has problems, set the count to -1
empCount = -1;
ex.printStackTrace();
}
}//END loadEmpNums
public int seqSearch (int target)
{
int ind = 0;
int found = -1;
while (ind < empCount) {
if(target==empNums[ind])
{
found = ind;
ind = empCount;
}
else
{
++ind;
}
}
return found;
}
}//END class Payroll
Are you reading in from a txt file or are they entering the data in when you run the program?
Related
A short flight of stairs will be called a construction of cubes in which each next level consists of a strictly larger number of cubes than the previous level, if we count the levels from top to bottom. You need to count the number of ladders that can be built exactly from n cubes.
My solution to this task doesn't pass the time test. To fix this, I decided to try to rewrite the recursive function to the usual one, but so far it has not worked out very well.
public class main {
int n;
public static int counts(int prev_level, int n) {
if (n == 0){
return 1;
}
int count = 0;
for (int level =1; level<prev_level; level++){
if((n-level)<0)
break;
count += counts(level,n-level);
}
return count;
}
public static void main(String[] args) {
int n;
int res = 0;
int count = 0;
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
n = Integer.parseInt(sc.nextLine());
res = counts(n+1,n);
}
} catch(IOException e) { System.out.println("Input error"); }
try{
FileOutputStream writer = new FileOutputStream("output.txt");
PrintStream p = new PrintStream(writer);
p.println(res);
writer.close();
} catch(IOException e) { System.out.println("Output error"); }
}
}
I am trying to load data from a txt file and it will only read one line of the txt file. When I specify what the int I variable is in my for loop within my loadData method it will print that particular line. I am not sure why it won't just add and print all my data.
I tried using an outer for loop to see if would print and add the data that way, but no luck
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
Here is the contents of the txt file I am using:
50.00
10
James,Smith,50.0
Michael,Smith,50.0
Robert,Smith,50.0
Maria,Garcia,50.0
David,Smith,50.0
Maria,Rodriguez,50.0
Mary,Smith,50.0
Maria,Hernandez,50.0
Maria,Martinez,50.0
James,Clapper,50.0
Every Time you put a BingoPlayer at Index 0 .
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
you have to define static counter variable where array of BingoPlayer is defined.
define count variable static
static BingoPlayer [] test;
static int count = 0;
and chane the add function definition like this.
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}
I am trying to create a program that will read from a .txt file that is formatted as such:
Total number of students
Name
Score1
Score2
Score3
Name
Score1
etc
My current code is this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are.
Current output:
Total
Name [score1 score2 score3]
etc
Desired output:
Total
Name score1 score2 score3 (rather than with the [] )
etc
Any help is greatly appreciated.
More structural way to do this :
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
The toString method of a List will return it in that format. If you want a different format, you can do this with a Stream:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Streams may get you accused of plagiarism, you will need to concatenate the elements yourself the long way.
This is the efficient solution that uses a StringBuilder and no Lists. A StringBuilder is basically a class that helps you to build string. Pretty straightforward.
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores.
I'm trying to create a lotto, where you have to read in a data file and match the numbers read in to winning numbers given through the console, my problem is that in the for loop where i read in the players numbers, it reads in fine, i even did a
system.out.print(ticketList.get(i).getNumbers()[j]+" ");
that checked if the numbers were correct, which they were, but when i did the same line of code outside the for loop where i add the instance of a ticket to the arraylist
ticketList.add(new Ticket(Players[i],ticketnumbers));`
It all gets over taken by the last instance ticket that was created, but the wierd part is, its only the player numbers that get over taken, not the player names, so thats what really threw me off, I've been sitting on it for a while trying to find stuff, but I've come up empty so far, any help would be appreciated!
I wanna say that the rest of the code works, because if i put the winning numbers as the last persons numbers he wins the lotto lol. I just know that when i try to match the number arrays it only uses the last persons numbers instead of everyone's individual numbers, so thats why that piece of code does not work.
public class Lottery{
static ArrayList<Ticket> ticketList = new ArrayList();
public static void scanFile() throws FileNotFoundException
{
String fileName;
int[] WinningNumbers = new int[6];
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
fileName = scan.nextLine();
System.out.println("Enter the winning Lottery Numbers");
for(int i =0; i<WinningNumbers.length;i++)
{
WinningNumbers[i] = scan.nextInt();
}
scan.close();
int NumberofTickets;
File file = new File(fileName);
Scanner scanInput = new Scanner(file);
NumberofTickets = scanInput.nextInt();
scanInput.nextLine();
String[] PlayersName = new String[NumberofTickets];
int[] ticketnumbers = new int[6];
for(int i=0; i < NumberofTickets;i++)
{
scanInput.nextLine();
PlayersName[i] = scanInput.nextLine();
scanInput.nextLine();
for(int j = 0 ; j<6;j++)
{
ticketnumbers[j] = scanInput.nextInt();
}
if(i != NumberofTickets-1)
scanInput.nextLine();
ticketList.add(new Ticket(PlayersName[i],ticketnumbers));
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
for(int i=0; i < NumberofTickets;i++)
{
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
checkTickets(WinningNumbers,NumberofTickets);
scanInput.close();
}
public static void checkTickets(int[] winningNumbers, int NumberofTickets)
{
int[] winnersMatchedNumbers = new int[6];
for(int i =0; i<NumberofTickets; i++)
{
int counter = 0;
if(winningNumbers[j] == ticketList.get(i).getNumbers()[j])
{
counter = counter+1;
}
}
winnersMatchedNumbers[i] = counter;
}
Winners(winnersMatchedNumbers,NumberofTickets);
}
public static void Winners(int[] matchedNumbers, int NumberofTickets)
{
for(int i = 0; i<NumberofTickets;i++)
{
System.out.println(ticketList.get(i).getTicketName()+ " matched "+ matchedNumbers[i]+" and won "+ ticketList.get(i).getWinnings(matchedNumbers[i]));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
scanFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the other class i am using is here
public class Ticket
{
private String ticketName;
private int[] personNumber = new int[6];
public Ticket(String Name,int[] ticketNumbers)
{
ticketName = Name;
personNumber = ticketNumbers;
}
public String getTicketName()
{
return ticketName;
}
public int[] getNumbers()
{
return personNumber;
}
public int getWinnings(int count)
{
int winningsAmount;
switch(count)
{
case 3: winningsAmount = 10;
break;
case 4: winningsAmount = 100;
break;
case 5: winningsAmount = 10000;
break;
case 6: winningsAmount = 1000000;
break;
default: winningsAmount = 0;
break;
}
return winningsAmount;
}
}
It seems that when I create my scanner I get this error. I have tried to solve this by searching the error name, but have so far been unsuccessful in getting the message to stop appearing.
Code:
import java.util.Scanner;
public class PrintQueue {
//Instance variables
private Queue<Job> pq;
//Constructor
public PrintQueue() {
pq = new Queue<Job>();
}
//Adds a job object to the end of the queue
public void lpr(String owner, int jobId) {
Job j = new Job(owner, jobId);
pq.enqueue(j);
}
//Enumerates the queue
public void lpq() {
Job curr = pq.first();
for (int i = 0; i < pq.size(); i++) {
System.out.println(curr);
curr = pq.next();
}
}
//Removes the first entry in the queue if the input integer matches the integer contained within the job object
public void lprm(int jobId) {
if (pq.first().getJobId() == (jobId))
pq.dequeue();
else
System.out.println("Unable to find jobId.");
}
//Removes all objects that contain the input String
public void lprmAll(String owner) {
Job curr = pq.first();
for (int i = 0; i < pq.size(); i++) {
if (curr.getOwner().equals(owner))
pq.dequeue();
curr = pq.next();
}
}
//Demo
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
PrintQueue myPQ = new PrintQueue();
String name;
int id;
for (int i = 1; i <= 5; i++) {
System.out.print("Enter owner and id: ");
name = k.next();
id = k.nextInt();
myPQ.lpr(name, id);
}
System.out.println("Print Queue");
myPQ.lpq();
myPQ.lprm(101);
myPQ.lprmAll("ronaldinho");
System.out.println("Print Queue");
System.out.println("\n\n");
myPQ.lpq();
}
}
Part where I get the error:
Scanner k = new Scanner(System.in);
That's because you're never closing the Scanner. Change your code to:
Scanner k = null;
try {
k = new Scanner(System.in);
//do stuff with k here...
} finally {
if( k != null )
k.close();
}
It seems that it is rather warning than error. However it is good practice to solve it.
Actually you just have to call k.close(); in the end of your method.
The best practice is to call close in finally block: this guarantees that the resource is closed whenever exception is thrown or not;
Scanner k = null;
try {
k = new Scanner(System.in);
........
} finally {
if (k != null) {
k.close();
}
}
Fortunately java 7 provides makes this syntax less verbose:
try (
Scanner k = new Scanner(System.in);
) {
.... // use k
}
When object of any class that implements Closable is created in special section of try block that marked with regular brackets () you do not have to write finally block: it is added by compiler.