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");
}
public clas Qyteti {
public float getSiperfaqja() {
return siperfaqja;
}
}
public clas Shteti {
Qyteti [] qytetet;
public void qytetiMeIVogel() {
}
}
This is my code, i created an obj array named qytetet My homework is
to find the smallest city in array calculating by square surface.
qytetiMeIVogel should to calculate the smallest square surface.
qyteti = city
siperfaqja = square surface
There isn't really much to go on, but here is how I would do it:
public class City {
private int squareSpace[];
public void getData(){
Scanner sc = new Scanner(System.in);
squareSpace[] = new int[10];
System.out.println("Please enter the square spaces of 10 cities\n");
for(int i=0;i<10;i++) {
sqaureSpace[i]=sc.nextInt();
}
//sc.close();
}
public int findMin(){
int minValue=squareSpace[0];
for(int i=1;i<10;i++) {
if(squareSpace[i]<minValue)
minValue=squareSpace[i];
}
}
I have assumed a static value of 10 here, but you can go ahead and assume any value. Now all you need to do is call the getData() and findMin() wherever required.
Here is the code:
import java.util.Scanner;
public class sending {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(first);
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(String first, String second){
first = ("Give me a number and I run down and add five to it");
second = ("Lol");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
As you can see I am new to this and I am having a problem with the main method and the method giveMe.
I want to have giveMe work as a collection of strings that I can call when I need them.
But when I try the above example I eclipse tells me that "first cannot be resolved to a variable" on line six String text = giveMe(first);
What am I doing wrong?
You are trying to use an enum and you never declared one... declare your enum like this outside your Main.
enum s {FIRST, SECOND} //add this
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(s.FIRST); //add the s. so it knows to use your enum
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
Then you want to modify your method to take an enum instead like this
public static String giveMe(s string) {
switch (string) {
case FIRST:
return "Give me a number and I run down and add five to it";
case SECOND:
return "Lol";
}
return "invalid string";
}
Beginner, your problem is resolved.
Firstly declaration is important in java. "First" variable is not intailzed in your block of code. Ideally it is not necessary for your scenario.
Try this
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe();
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(){
String first = ("Give me a number and I run down and add five to it");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable
adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132
And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1
The problems with my code are as follows:
It doesn't sort based off the index
It gives me an error at runtime with the code: Arrays.sort(c);
Please help with suggestions
Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Prog4 {
static Scanner input;
static File filename;
/**
* This function displays the menu for the user to choose an option from
*/
public void menu() {
System.out.println("Option 1: Sort by VENDOR: ");
System.out.println("Option 2: Sort decreasing number by MMAX: ");
System.out.println("Option 3: Sort decreasing number by CACH: ");
System.out.println("Option 4: Sort decreasing number by PRP: ");
System.out.println("Option 5: Quit program");
}
/**
* Constructor to handle the cases in the menu options
* #throws FileNotFoundException
* #throws IOException
*/
public Prog4() throws FileNotFoundException {
//Accepts user input
Scanner in = new Scanner(System.in);
//calls the menu method
menu();
//Initializes the run variable making the program loop until the user terminates the program
Boolean run = true;
//While loop
while (run) {
switch (in.nextInt()) {
case 1:
System.out.println("Option 1 selected");
System.out.println("Sorted by vendor:");
filename = new File("machine.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new Array of String type
String array [] = new String[10];
//while it has next ..
while (input.hasNext()) {
//Initialize variable
int i = 0;
//store each word read in array and use variable to move across array array[i] = input.next();
//print
System.out.println(array[i]);
//so we increment so we can store in the next array index
i++;
}
case 2:
System.out.println("Press any key to continue");
Scanner input2 = new Scanner(System.in);
String x = input2.nextLine();
if (x.equals(0)) continue;
System.out.println("Option 2 selected") ;
Computer[] c = new Computer[10];
filename = new File("machine.txt");
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Arrays.sort(c);
while (input.hasNextLine()) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
}
}
/**
* Main method
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
//Calls the constructor
new Prog4();
//static Scanner input;
}
public static void quickSort(int arr[], int left, int right) {
if (left < right) {
int q = partition(arr, left, right);
quickSort(arr, left, q);
quickSort(arr, q+1, right);
}
}
private static int partition(int arr[], int left, int right) {
int x = arr[left];
int i = left - 1;
int j = right + 1;
while (true) {
i++;
while (i < right && arr[i] < x)
i++;
j--;
while (j > left && arr[j] > x)
j--;
if (i < j)
swap(arr, i, j);
else
return j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Comparator class:
import java.util.Comparator;
class Computer implements Comparable<Computer> {
private String vendor;
private int mmax;
private int cach;
private int php;
public Computer(int value) {
this.mmax = value;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getMmax() {
return mmax;
}
public void setMmax(int mmax) {
this.mmax = mmax;
}
public int getCach() {
return cach;
}
public void setCach(int cach) {
this.cach = cach;
}
public int getPhp() {
return php;
}
public void setPhp(int php){
this.php = php;
}
#Override
public int compareTo(Computer m) {
if (mmax < m.mmax) {
return -1;
}
if (mmax > m.mmax) {
return 1;
}
// only sort by height if age is equal
if (cach > m.cach) {
return -1;
}
if (cach < m.cach) {
return 1;
}
if (php > m.php) {
return -1;
}
if (php < m.php) {
return 1;
}
return 0;
}
public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
#Override
public int compare(Computer p1, Computer p2) {
return p2.getMmax() - p1.getMmax();
}
};
}
The biggest problem is that the Computer classes do not get instantiated for each line that gets read.
As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.
I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.
Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
Create a blank ArrayList to store the Computer objects.
Iterate through the file and readLine
Call the Computer constructor using the String representing each line in the file within the while loop
Add the new Computer object to the computers ArrayList
Write 5 different comparators.
Based on user input, instantiate the correct comparator and pass it to the sort method
Print the sorted array
If you still face a problem, mention the specific point at which you like more clarity..
the repeated items in the text file should not be added to the list but this program is outputing every word from the list dont know why hasElement method is not working.I need to create an program object which should be called MTFencoder.java and it should accept the name of a text file as a command-line argument such that if there exists a text file called story.txt then your program could be invoked with the following command:
java MTFencoder test.txt
It should produce one line of output for each word of the input file, such that when a word is first encountered then the output is:
0 word
and if the word has been encountered before then the output is a single integer specifying the index of that word in a list of known words ordered according to the most recently used (MRU order).
import java.util.*;
import java.io.*;
class extmycase
{
public static void main(String [] args)
{
Scanner scan=null;
Scanner scan1=null;
wordlist word=null;
String s;
int count=0;
try
{
scan=new Scanner(new File(args[0]));
scan1=new Scanner(new File(args[0]));
while(scan1.hasNext())
{
scan1.next();
count++;
}
System.out.println("No.of words : " + count);
word = new wordlist(count);
while(scan.hasNext())
{
s=scan.next();
if(word.hasElement(s)==true)
{
System.out.println("has element");
}
else
{
word.add(s);
}
}
word.showlist();
}
catch(Exception e)
{
System.err.println("unable to read from file");
}
finally
{
// Close the stream
if(scan != null)
{
scan.close( );
}
if(scan1 !=null)
{
scan1.close();
}
}
}
}
the wordlist program is
import java.lang.*;
import java.util.*;
public class wordlist
{
public String data [];
private int count;
private int MAX;
public wordlist(int n)
{
MAX = n;
data = new String[MAX];
count = 0;
}
// Adds x to the set if it is not already there
public void add(String x)
{
if (count<MAX)
{
data[count++] = x;
}
}
// Removes x from set by replacing with last item and reducing size
public void replace(String x)
{
for(int i=0;i<count;i++)
{
if(data[i]==x)
{
data[count]=data[i];
for(int j=i;j<count;j++)
data[j]=data[j+1];
}
}
}
// Checks if value x is a member of the set
public boolean hasElement(String x)
{
for(int i=0;i<=count;i++)
{
if(data[i].equals(x))
{
return true;
}
}
return false;
}
public int findIndex(String x)
{
for(int i=0;i<=count;i++)
{
if(data[i].equals(x))
{
return i;
}
}
return 0;
}
public void showlist()
{
int l=0;
for(int i=0;i<count;i++)
{
System.out.println(data[i]);
l++;
}
System.out.println(l);
}
}
Your wordlist will never contain any elements. It is constructed, which sets everything to 0, and then you see whether it contains words, with of course it will never do. Also, both scanners point to the same file, so every word that exists from one will have to exist in the other, and all words will be found making this semi-redundant in the first place.