linked list manual entered by keyboard - java

when creating the list manually by keyboard I have the following drawback, the variable nodo only stores the current value. ListaEnlazada1 nodo = new ListaEnlazada1();
package lista.enlazada1;
import java.util.Scanner;
public class ListaEnlazada1 {
public String marca;
public String modelo;
public int kilometraje;
public ListaEnlazada1 nodosiguiente;
public static void main(String[] args) {
/* enter the number of nodes to be created */
Scanner leer= new Scanner(System.in);
System.out.println("Digite la cantidad de nodos a ingresar)");
int n,contador=0;
n=leer.nextInt();
/* the three data of the node is entered */
for (int i =1; i <= n; i++){
ListaEnlazada1 nodo = new ListaEnlazada1();
System.out.print("ingrese la marca ");
nodo.marca=leer.next();
System.out.print("ingrese el modelo ");
nodo.modelo=leer.next();
System.out.print("ingrese el kilometraje ");
nodo.kilometraje=leer.nextInt();
/* the node is created */
if(contador==0){
nodo.nodosiguiente = null;
contador ++;
} else {
nodo.nodosiguiente = nodo;
contador ++;
}
/* nodes are printed */
for ( i =1; i <= n; i++){
System.out.println("marca " +nodo.marca+ "\n");
System.out.println("modelo " +nodo.modelo+ "\n");
System.out.println("kilometraje " +nodo.kilometraje+ "\n");
System.out.println("apuntador " +nodo.nodosiguiente + "\n");
}
}
}
}
I need to change the code so that the variable changes the name every time I enter the for, for example the first iteration node1, the second iteration node2, etc. what I have tried nothing has worked. the exercise must be done without the linked list library

To display the current node's position in the series, consider the following:
for(int i = 1; i <= n; i++) {
System.out.println("----------");
System.out.println("Ingrese los datos del nodo " + i);
/* user input */
}
You might as well consider displaying information about each node after all nodes have been entered so that the program's output is more readable. Since you store each node in the node before it, you could try this to cycle through them:
ListaEnlazada actual = primerNodo; // save the first node somewhere before user input
imprimirNodo(actual);
while((actual = actual.nodosiguiente) != null) {
imprimirNodo(actual);
}
where the imprimirNodo(nodo) method is the following:
static void imprimirNodo(ListaEnlazada1 nodo) {
System.out.println("----------");
System.out.println("Marca: " + nodo.marca); // No need to break the line manually.
System.out.println("Kilometraje: " + nodo.kilometraje);
/* Note that printing nodo.nodosiguiente may lead to
* unreadable output unless you override toString() */
System.out.println("Apuntador: " + nodo.nodosiguiente);
}

Related

Scanner.hasNext() Causing Input to be Needed Twice

I am working on some homework and have encountered a problem. The program creates a Tree, outputs pre/in/postorder traversals, then saves them to multiple files. The problem I'm having is getting the input. When you type in the input, after you're done typing in what should be the values of different Nodes, you may either type "done" or "exit". "Done" continues the program with the given input, while "exit" just closes the program. The weird thing is, you don't need to type the values of the Nodes twice to create those Nodes later on in the code, but you do have to type "done" or "exit" twice to get the program to listen to you. The code in question is here:
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(scanner.hasNext() && !response.equals("exit") && !response.equals("done")) {
fileWriter.write(response + " ");
response = scanner.next();
}
I have found that removing scanner.hasNext() gets it to function properly, but then it takes away sensing the EOF which is necessary for this assignment.
Here are the full three classes used in the program:
P0:
/**
* Sources for this class:
* https://www.w3schools.com/java/java_regex.asp
* https://stackoverflow.com/questions/14353947/how-to-represent-a-single-space-character-in-a-square-bracket-group
* https://upload.wikimedia.org/wikipedia/commons/1/1b/ASCII-Table-wide.svg
*
* Sources for shell script and makefile:
* https://www.cyberciti.biz/faq/run-execute-sh-shell-script/
* https://www.dummies.com/article/technology/computers/operating-systems/linux/linux-how-to-run-make-150284/
* https://www.cs.swarthmore.edu/~newhall/unixhelp/javamakefiles.html
*/
package mikefitzgibbon.p0;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class P0{
public static void main(String args[]) {
File file = new File("file");
String input = "";
//there can only be one or 0 arguments in the command line operation
if(args.length > 1) {
System.out.println("Please only enter the name of 1 file.");
System.exit(1);
}
//if a filename is specified, try getting the input from it
else if(args.length == 1){
file = new File(args[0]);
}
//else read from System.in
else {
Scanner scanner = new Scanner(System.in);
String response;
file = new File("input");
try (FileWriter fileWriter = new FileWriter(file)) {
System.out.println("Please enter strings to put into the tree.");
System.out.println("Type \"done\" to end taking in input, and type \"exit\" to prematurely quit.");
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(scanner.hasNext() && !response.equals("exit") && !response.equals("done")) {
fileWriter.write(response + " ");
response = scanner.next();
}
//exits the program with OK return value
if(response.equals("exit")) {
System.out.println("Prematurely ending program now.");
System.exit(0);
}
}
catch(IOException e){
System.out.println("Had trouble writing to file from System.in.");
}
}
//scans file for strings until there are no more data or eof is reached
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextLine()){
input += scanner.nextLine() + " ";
}
scanner.close();
}
//exit the program is file name is invalid
catch(FileNotFoundException e){
System.out.println("The file name you entered does not exist.");
System.exit(2);
}
//checks input for characters outside of the appropriate ASCII range
for(char c : input.toCharArray()){
if(!Character.isLetterOrDigit(c) &! Character.isWhitespace(c)) {
System.out.println("Your file or console input was not readable."
+ "\nPlease only use alhpanumeric characters.");
System.exit(3);
}
}
//this is only used as a reference for the filename
if(file.getName().equals("input"))
file = new File("output");
//creates the tree from the input and then converts it to the output
Tree tree = new Tree(input);
//displays the input
System.out.println("Here is your input for the program.");
System.out.println(input);
System.out.println();
//writes to the files
System.out.println("Outputting data to files " +
file.getName() + ".preorder, " +
file.getName() + ".inorder, and " +
file.getName() + ".postorder.");
System.out.println();
System.out.println("Output for " + file +".preorder: ");
tree.printPreorder(file.getName());
System.out.println();
System.out.println("Output for " + file +".inorder: ");
tree.printInorder(file.getName());
System.out.println();
System.out.println("Output for " + file +".postorder: ");
tree.printPostorder(file.getName());
System.out.println();
System.out.println("Ending program now.");
}
}
Tree:
/**
* Sources for this class:
* https://www.w3schools.com/java/java_files_create.asp
* https://www.softwaretestinghelp.com/binary-search-tree-in-java/
* https://www.youtube.com/watch?v=WLvU5EQVZqY&ab_channel=TECHDOSE
*/
package mikefitzgibbon.p0;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Tree {
//nodes that make up this part of the tree
Node root;
//constructor calls the buildTree() function
public Tree(String input){
buildTree(input);
}
//takes a list of strings and a root node and creates the tree structure recursively using the addNode helper function
private void buildTree(String input) {
Scanner scanner = new Scanner(input);
//recursively builds tree with each word
while(scanner.hasNext()){
root = addNode(root,scanner.next());
}
}
private Node addNode(Node root, String value){
//checks root for null and sets it if it is
if(root == null){
root = new Node(value);
return root;
}
//compares the first letter of the input to the root's value and recursively traverses tere
else if(root.getValue().charAt(0) > value.charAt(0))
root.setLeftNode(addNode(root.getLeftNode(),value));
else if(root.getValue().charAt(0) == value.charAt(0))
root.setMiddleNode(addNode(root.getMiddleNode(),value));
else if(root.getValue().charAt(0) < value.charAt(0))
root.setRightNode(addNode(root.getRightNode(),value));
//return root if all else fails
return root;
}
//prints the tree printPreorder recursively
public void printPreorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".preorder")) {
printPreorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the preorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the preorder file.");
}
}
//helper function for printPreorder()
private void printPreorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
try{
String indent = "";
for(int a = 0 ; a < depth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.println(indent + root.getValue().charAt(0) + ":" + root.getValue());
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .preorder file.");
System.exit(4);
}
depth++;
printPreorder(fileWriter, root.getLeftNode(), depth);
printPreorder(fileWriter, root.getMiddleNode(), depth);
printPreorder(fileWriter, root.getRightNode(), depth);
}
//prints the tree printInorder recursively
public void printInorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".inorder")) {
printInorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the inorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the inorder file.");
}
}
//helper function for printInorder()
private void printInorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
int previousDepth = depth;
depth++;
printInorder(fileWriter, root.getLeftNode(), depth);
try{
String indent = "";
for(int a = 0 ; a < previousDepth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.print(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .preorder file.");
System.exit(4);
}
printInorder(fileWriter, root.getMiddleNode(), depth);
printInorder(fileWriter, root.getRightNode(), depth);
depth++;
}
//prints the tree printPostorder recursively
public void printPostorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".postorder")) {
printPostorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the postorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the postorder file.");
}
}
//helper function for printPostorder()
private void printPostorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
int previousDepth = depth;
depth++;
printPostorder(fileWriter, root.getLeftNode(), depth);
printPostorder(fileWriter, root.getMiddleNode(), depth);
printPostorder(fileWriter, root.getRightNode(), depth);
try{
String indent = "";
for(int a = 0 ; a < previousDepth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.print(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .postorder file.");
System.exit(4);
}
}
//getter and setter
public void setRoot(Node node) {
root = node;
}
public Node getRoot() {
return root;
}
}
Node:
/**
* Sources for this class:
* https://www.softwaretestinghelp.com/binary-search-tree-in-java/
*/
package mikefitzgibbon.p0;
public class Node {
//this is how the tree branches out, 3 children per node
Node left, middle, right;
String value = "";
public Node(String val) {
value=val;
}
//getters and setters
public void setRightNode(Node node) {
right=node;
}
public void setLeftNode(Node node) {
left=node;
}
public void setMiddleNode(Node node) {
middle=node;
}
public Node getRightNode() {
return right;
}
public Node getLeftNode() {
return left;
}
public Node getMiddleNode() {
return middle;
}
public String getValue() {
return value;
}
}
scanner.hasNext() will block (freeze the thread) until user input happens. You might think "No, it would return false, as currently there is no token available - there is no 'next'", but that's not how it works. There indeed may not currently be a next. But who knows what happens from here on out? Perhaps the user types CTRL+C, closing the pipe, thus, hasNext() will now return false, as there will never be a next token. Or, the user types something, and it will then return true, as now clearly there is a next token to be had. That's why it blocks: It cannot give a certain answer until you do something.
This may make no sense - keep in mind that 'standard input' is not the keyboard. It's... whatever stream is hooked up to standard input. By default that is a keyboard, but run your app with java -jar whatever.jar <somefile.txt and now it's that file. Which has a limited size. hasNext() would start returning false once you get to the 'end of the file'. You cannot normally ever get to the 'end of the keyboard', but the abstraction isn't designed solely for keyboards.
In other words, your code:
response = scanner.next();
while(scanner.hasNext() && ....
Will:
Read a token from standard input.
Will... read a token from standard input AGAIN (because hasNext() does that. If it works out, it returns true. If it turns out there is no token now nor will there ever be, it returns false).
This explain why you have to enter input twice. The solution is to remove the hasNext call there. Move it INTO the while loop. Instead of response = scanner.next() inside the loop, do something like:
if (!scanner.hasNext()) return; // or break, or System.exit(0), or whatever you want.
response = scanner.next();
}
I found that putting the scanner.hasNext() at the end of the expression fixed the problem, but I'm not entirely sure how. Here is the updated code:
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(!response.equals("exit") && !response.equals("done") && scanner.hasNext()) {
fileWriter.write(response + " ");
response = scanner.next();
}

How to change a specific parameters of the specific elements in an array-list based on another elements parameters

I am new to java but have been playing with array-lists and am now stuck.
I have an array list created off a class called Car with three parameters one of which is called times moved.
ArrayList:
private ArrayList<Car> list = new ArrayList<Car>() ;
Car class
public Car ( String licenseNum, String carStatus , int timesMoved)
{
licensePlate = licenseNum ;
status = carStatus ;
moved = timesMoved;
}
I am reading input of a file that is supposed to be like a garage and says if a car is "Arriving" or "Departing"
I am trying to write a code using an if statement that says if the status is "Departing" then the current element gets deleted the all elements in front of it add one to their "times moved parameter"
The part I am stuck on is the one where, based on the element getting deleted, all the elements in front of it in the array list add one to their "times moved" parameter.
Would anyone give me some advice on how it would be possible to do that?
I came up with this but it does not seem to work
public void carDepart()
{
for ( int i = 0 ; i < list.size() ; i++ )
{
Car current = list.get( i ) ; // get next car
if (current.getStatus().equals("DEPART"))
{
int pos = list.indexOf(i);
for ( int j = 0 ; pos < j ; j++)
{
current.setTimesMoved(1 + current.getTimesMoved());
}
list.remove(i);
}
break;
}
}
Second method
public void moveCarInGarage()
{
for ( int i = 0 ; i < list.size() ; i++ )
{
Car current = list.get( i ) ; // get next car
if (current.getStatus().equals("ARRIVE"))
{
currentCars++;
if (currentCars <= 10)
{
System.out.println("Car with license plate" +
current.getLicenseNum() + " has been moved into the garage");
}
else
{
System.out.println("The garage is full at this " +
"time so come back later");
}
}
else
{
currentCars--;
System.out.println("Car with license plate" +
current.getLicenseNum() + " is departing and has been moved "
+ current.getTimesMoved() + " times" );
}
}
}
Here is an example of what you can do. In it, I assume you are using getters and setters. You can also call the attributes directly assuming you've set the access modifiers in a way that allows you to do so.
All I did was create a new method called incrementTimesMoved() that iterates through your ArrayList and increments all the "moved" attributes in it's elements until it gets to the one with a given index. It removes this, and stops running.
public class MCVE {
public static void main(String[] args) {
// IMO list isn't very descriptive, so I changed it to carList.
ArrayList<Car> carList = new ArrayList<>();
// Add a bunch of values to carList here.
for(int i = 0; i < carList.size(); i++) {
if(carList.get(i).getStatus().equals("Departing")) {
incrementTimesMoved(i, carList);
return; // stops the method
}
}
}
// only static because I am calling in the main() function
private static void incrementTimesMoved(int index, ArrayList<Car> carList) {
for(int i = 0; i < carList.size(); i++) {
if(i == index) {
carList.remove(index);
return;
}
carList.get(i).setMoved(carList.get(i).getMoved() += 1);
}
}
}

Dice roller Java returns less random results

i'm trying to make a little program thar throws "reservaDados" number of dice and compare the "dado" (who is a number between 1-10) to a specified dificulty. Then i want to print the count of the number of exits, fails and ultrafails, but i seem to have a problem with the number of times the loop works, it only prints 9 results and i don't seem to find why, i supose that it has to do something with the counter i?
import java.util.*;
public class ProgramTUI {
public static void main(String[] args) {
Scanner var = new Scanner(System.in).useLocale(Locale.ENGLISH);
System.out.print("Cuantos dados lanzas?");
int reservaDados = var.nextInt();
System.out.print("Cual es la dificultad?");
int dificultad = var.nextInt();
int i = 0;
int numero_exitos = 0;
int numero_fracasos = 0;
int numero_pifias = 0;
while (i < reservaDados) {
i++;
int dado = (int) (Math.random() * 10) + 1;
if (reservaDados == i) {
System.out.println("Has sacado " + numero_exitos + " exitos, " + numero_fracasos
+ " fracasos, " + numero_pifias + " pifias");
} else if (dado == 1) {
numero_pifias++;
} else if (dado < dificultad) {
numero_fracasos++;
} else {
numero_exitos++;
}
}
}
}
In the last iteration, no more counting is done, only the result is printed. So you effectively miss one iteration.
Could be fixed by removing the first else, or by doing one extra iteration.
But just take the whole result printing out of the loop and place it directly after the loop. That will make the intent of the code much clearer.
Thilo is right, in the last pass of the loop it dosn't count the dice because ther is a print first, i just taked out the print, and pasted at the end like this:
import java.util.*;
public class ProgramTUI {
public static void main(String[] args) {
Scanner var = new Scanner(System.in).useLocale(Locale.ENGLISH);
System.out.print("Cuantos dados lanzas?");
int reservaDados= var.nextInt();
System.out.print("Cual es la dificultad?");
int dificultad= var.nextInt();
int i=0;
int numero_exitos=0;
int numero_fracasos=0;
int numero_pifias=0;
while (i < reservaDados){
i++;
int dado= (int) (Math.random() * 10) + 1;
if (dado == 1) {numero_pifias++;}
else if (dado < dificultad) {numero_fracasos++;}
else {numero_exitos++;}
if (reservaDados == i){System.out.println("Has sacado "+numero_exitos+" exitos, "+numero_fracasos+" fracasos, "+numero_pifias+" pifias");}
}
}
}
And it was fixed, thanks!

Error on: Binary search tree on java with text file

Here's a program that will accept a text file (.txt, not Microsoft word or pdf stuff, just a basic text file) as a COMMAND LINE ARGUMENT and store each word (accepting ALL punctuation as if it were a space character, including apostrophe's) in a binary tree. Each node in the tree stores an ArrayList which holds the number of times that word occurs(first element) and each position in the text file that it occurs (all following elements). The user is shown the total number of words, and you can search for a word to see how many times and where in the file it is stored.
The code is not mine the autor is MasudKhan, i'm learning with it how to do my own code for a similar program.
I have been having some trouble finding the error with this code and why it's not working, the error message is:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at A3Driver.main(A3Driver.java:10)"
A3Driver.java
/**
Assignment3
This class is a driver for a program which reads in a file,
whose name is given as a command line argument, and stores each
word as well as how many occurences of that word and the positions of
each occurence in the text file. The program then offers to allow
the user to search for any input word and produce the info for it,
if any.
*/
import java.io.*;
import java.util.*;
public class A3Driver
{
/**
main method for Binary word search program.
*/
public static void main(String[] args)
{
WordBST newTestWordBST = new WordBST(new File(args[0]));
System.out.println("Total number of words in file: " +
WordBST.wordPosition);
System.out.println("Number of unique words in file: " +
WordBST.uniqueWordCount);
System.out.print("Most used word: " + WordBST.mostUsedWord);
System.out.println(", times used: " + WordBST.highestCount);
System.out.println("\n\n");
Scanner keyboard = new Scanner(System.in);
String input = "";
while(!input.equals("n"))
{
System.out.print("Search for word (y/n)? ");
input = keyboard.nextLine();
if(input.toLowerCase().equals("y"))
{
System.out.print("Enter word: ");
newTestWordBST.searchBinaryTree(keyboard.nextLine());
}
}
System.out.println("Thank you, goodbye.");
/**
To output all tree info, uncomment this section.
newTestWordBST.inOrderTraverse();
*/
}
}
WordBST.java
/**
Assignment3
This class holds a Binary search tree of WordBSTNodes.
*/
import java.io.*;
import java.util.*;
public class WordBST
{
WordBSTNode root;
static int wordPosition, uniqueWordCount = 0, highestCount;
static String mostUsedWord;
/**
Constructor: initializes the root to null.
*/
public WordBST()
{
root = null;
}
/**
Constructor: initializes root to parameter value.
#param theRoot the root of this WordBST object
*/
public WordBST(WordBSTNode theRoot)
{
root = theRoot;
}
/**
Constructor: initializes root to hold nodes containing the words and
data from the parameter file.
#param text the input file containing words
*/
public WordBST(File text)
{
try
{
BufferedReader bR = new BufferedReader(new FileReader(text));
root = readBinaryTree(bR);
}
catch(IOException e)
{
System.out.println("Error reading file. Exiting.");
System.exit(1);
}
}
/**
Wrapper method for the recursive add method.
#param item the item to add to the BST
*/
public void add(String item)
{
root = add(root, item);
}
/**
Postcondition: uses recursion to add item to the BST node in the
appropriate position, or add information to the matching node.
#param localRoot the local node being checked in the current call
#param item the item to add to the BST
*/
private WordBSTNode add(WordBSTNode localRoot, String item)
{
if(localRoot == null) // item not in tree - add it
{
uniqueWordCount++; // total distinct word count
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(1);
temp.add(wordPosition);
return new WordBSTNode(item, temp);
}
else if(item.compareTo(localRoot.word) == 0) // item == localRootData
{
localRoot.countAndPos.set(0, localRoot.countAndPos.get(0) + 1);
localRoot.countAndPos.add(wordPosition);
if(localRoot.countAndPos.get(0) > highestCount)
{
highestCount = localRoot.countAndPos.get(0);
mostUsedWord = localRoot.word;
}
return localRoot;
}
else if(item.compareTo(localRoot.word) < 0) //item < localRootData
{
localRoot.leftTree = add(localRoot.leftTree, item);
return localRoot;
}
else // item > localRootData
{
localRoot.rightTree = add(localRoot.rightTree, item);
return localRoot;
}
}
/**
Postcondition: performs an inorder traversal.
*/
public void inOrderTraverse()
{
inOrderTraverse(root);
}
/**
Perform an inorder traversal.
#param localRoot the current node being traversed
*/
private void inOrderTraverse(WordBSTNode localRoot)
{
if(localRoot.leftTree != null) // left
{
inOrderTraverse(localRoot.leftTree);
}
// middle
//output current root
System.out.print(localRoot.word);
for(int i = 0; i < localRoot.countAndPos.size(); i++)
{
System.out.print(", " + localRoot.countAndPos.get(i));
}
System.out.println();
if(localRoot.rightTree != null) // right
{
inOrderTraverse(localRoot.rightTree);
}
}
/**
Wrapper method for searchBinaryTree recursive method.
#param searchWord the String word to search for
*/
public void searchBinaryTree(String searchWord)
{
searchBinaryTree(searchWord, root);
}
/**
Postcondition: if word is found in the search, it is output along with
occurrence information, and if it is not found, not-found info is output.
#param searchWord the word to search for
#param localRoot the localRoot being checked in the current call
*/
public void searchBinaryTree(String searchWord, WordBSTNode localRoot)
{
if( (searchWord.compareTo(localRoot.word) < 0) &&
(localRoot.leftTree != null) )
{
searchBinaryTree(searchWord, localRoot.leftTree);
}
else if( (searchWord.compareTo(localRoot.word) > 0) &&
(localRoot.rightTree != null) )
{
searchBinaryTree(searchWord, localRoot.rightTree);
}
else if(searchWord.compareTo(localRoot.word) == 0)
{
System.out.println("Position number(s) of occurence(s):");
for(int i = 1; i < localRoot.countAndPos.size(); i++)
{
System.out.println("word #" + localRoot.countAndPos.get(i));
}
System.out.println("Word found.");
System.out.println("Occurences: " +
localRoot.countAndPos.get(0));
}
else
{
System.out.println("Word does not exist.");
}
}
/**
#param bR the bufferedReader to read from
#return returns a node containing the info from the file which the input
BufferedReader is reading from
*/
public WordBSTNode readBinaryTree(BufferedReader bR)
{
String data = "";
String temp;
try
{
while(bR.ready())
{
data = data.concat(bR.readLine().toLowerCase() + "\n");
}
if(data == "")
{
return null;
}
}
catch(IOException e)
{
System.out.println("Error reading file. Exiting.");
System.exit(1);
}
return readBinaryTree(
new StringTokenizer(data,
" \t\n\r\f.,!`'-\"\\:()[]{}=+_*&^%$##?<>;|/~"));
}
/**
#param inputST the StringTokenizer to repeatedly add words from
#return returns a node containing the info from the file which the input
BufferedReader is reading from
*/
public WordBSTNode readBinaryTree(StringTokenizer inputST)
{
wordPosition = 1;
ArrayList<Integer> tempArrayList =
new ArrayList<Integer>(wordPosition++);
tempArrayList.add(1);
WordBST tempBST = new WordBST(
new WordBSTNode(inputST.nextToken(), tempArrayList));
highestCount = 1;
mostUsedWord = tempBST.root.word;
while(inputST.hasMoreTokens())
{
tempBST.add(inputST.nextToken());
wordPosition++; // current position, and total words in file
}
return tempBST.root;
}
}
WordBSTNode.java
/**
Assignment3
This class holds a node for a binary search tree. The node includes
a pointer to it's left subtree and it's right subtree, as well as String
data, and an ArrayList containing the number of occurences of the
data in the user's input file in the first position, followed by the
word number in each following position.
*/
import java.util.*;
public class WordBSTNode
{
WordBSTNode leftTree;
WordBSTNode rightTree;
String word;
ArrayList<Integer> countAndPos;
/**
Constructor: no arg constructor must never be used to avoid
confusion between a null node element and a null element content.
*/
public WordBSTNode()
{
System.out.println("Cannot creat empty node, sorry.");
}
/**
Constructor: initializes parent, word, and countAndPos instance
variables.
#param theWord the word to be stored in this node
#param theCountAndPos an ArrayList containing this node's word's
count and position's
*/
public WordBSTNode(String theWord, ArrayList<Integer> theCountAndPos)
{
leftTree = null;
rightTree = null;
word = theWord;
countAndPos = theCountAndPos;
}
}
Any help is really apreciated.

'.class' expected when trying to pass a double Array in Java

I'm a newbie of Java, and while studying it I found out an exercise who killed my brain for almost 7 hours. I tried everything I knew, I read the chapter of the book once again, I've googled for an answer for hours, and even used the Search button here, but nothing helped me. I can't understand what the heck is wrong with line 26:
import java.util.Scanner;
public class Esercizio {
public static void main(String[] args) {
Scanner tastiera = new Scanner(System.in);
System.out.println("");
System.out.println("Scrivi un intero per la lunghezza dell'Array.");
System.out.println("");
int lunghezzaArray = 0;
lunghezzaArray = tastiera.nextInt();
double[] valore = new double[lunghezzaArray];
System.out.println("");
System.out.println("Ora scrivi i numeri che vuoi dentro, possibilmente in ordine crescente.");
System.out.println("");
for (int i = 0; i < valore.length; i++) {
valore[i] = tastiera.nextDouble();}
boolean risultato = true;
risultato = strettamenteMaggiore(valore[]); // Here is the line!
System.out.println("Uscira' True o False? Risultato = " + risultato);
}
public static boolean strettamenteMaggiore(double[] valore) {
boolean risultato = false;
for (int i = 0; i < valore.length; i++) {
if (valore[i] < valore[i + 1]) {
risultato = true;}
else
risultato = false;
}
return risultato;
}
}
The program is in Italian, but I guess it doesn't matter, variables and stuff names are just, names.
Any idea of what's wrong with the code? This is the first time I encounter this error with Arrays and Methods.
Edit:
The exercise asks to write a static method called 'strettamenteCrescente(double[] in)' which returns "true" if every value of the array supplied to the input is greater than the value that precedes it. Else, "false".
Balduz has it right. Just remove the brackets []. In Java, brackets are used to declare the array, as in double[] valore, or to refer to an element of the array, as in valore[i]. To refer to the array object itself, you just use the array name.
You are passing a POSITION of the array to the method, but the method is expecting the whole array.
The solution is:
risultato = strettamenteMaggiore(valore); // Here is the linee
instead of
risultato = strettamenteMaggiore(valore[]); // Here is the line!

Categories

Resources