I Need help with the program. I keep getting this error which happens at the runtime. I also would like it if someone could let me know if anything else is wrong with it. Thanks!
import java.io.*;
import java.util.*;
public class Lab2 {
private String[][] data;
public void readFile() {
//Instantiate file object
File f = new File("nameslist.txt");
try {
Scanner input = new Scanner(f);
//open file for reading
int x = input.nextInt();
data = new String[x][3];
int i = 0;
while (input.hasNext() && i < data.length) {
String name = input.nextLine();
String[] nameArray = name.split(" ");
data[i][0] = nameArray[0];
data[i][0] = nameArray[1];
data[i][0] = nameArray[2];
i++;
}
input.close();
} catch (IOException e) { //opening failed
e.printStackTrace();
}
}
public void outputNames() {
System.out.println("First Name\tMiddle Name\tLast Name");
for (int i = 0; i < data.length; i++)//output all elements
{
System.out.println(data[i][0] + "\t\t" + data[i][1] + "\t\t" + data[i][2]);
}
}
public int nameSearch( String key) {
for (int i = 0; i < data.length; i++) {
if (key.equalsIgnoreCase(data[i][0])||key.equalsIgnoreCase(data[i][1])||key.equalsIgnoreCase(data[i][2])) {
return i;
}
}
return -1;
}
public void hashCodeMethod() {
long hash = 5381;
for (int i = 0; i < data.length; i++){
long hashCode = 0;
for (int j = 0; j < data[i].length; j++){
for (int k = 0; k < data[i][j].length(); k++){
data[i][j].charAt(i);
hashCode += ((hash << 5) + hash) + data[i][j].charAt(i);
}
}
}
}
}
End class Lab2
package lab.pkg2;
public class Lab2Client{
public static void main(String[] args) {
Lab2 test = new Lab2();
test.readFile();
test.outputNames();
test.nameSearch("Gamaliel");
test.hashCodeMethod();
}
}
I am getting this error at runtime:
Exception in thread “main” java.lang.RuntimeException:Uncompilable source code -
Erroneous tree type: lab.pkg2.Lab2
Delete NetBeans cache ~/.netbeans/6.9/var/cache/index/ (everything inside that folder)
Change 6.9 for your version.
Related
What should be entered in intellij IDEA command line arguments? I have a file input.txt and output.txt (a matrix is read from the first file, a new one is displayed in the second one) what should be passed to the command line arguments and how to do it syntactically correctly?
I have the program logic, it works in idea, but I need to run it via console, and that requires command line arguments.
package vsu.cs.vega;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Solution output = new Solution();
String error = "You entered a non-rectangular matrix, please check the data and
re-enter.";
try {
output.readMtx();
}
catch (ArrayIndexOutOfBoundsException exception){
System.err.print(error);
}
}
}
package vsu.cs.vega;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.ArrayIndexOutOfBoundsException;
public class Solution {
void readMtx() throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("readInFileOutFromFile/src/vsu/cs/vega/input.txt"));
ArrayList<String> lines = new ArrayList<>();
while (br.ready()) {
lines.add(br.readLine());
}
int matrixHeight = lines.size();
int[][] matrix = new int[matrixHeight][];
for(int i = 0; i < matrixHeight; ++i) {
String[] nums = lines.get(i).split("\s*,\s*");
matrix[i] = new int[nums.length];
for(int j = 0; j < nums.length; ++j) {
matrix[i][j] = Integer.parseInt(nums[j]);
}
}
int[][] matrixForOutput = calc(matrix);
try(PrintWriter out = new PrintWriter(new
FileOutputStream("readInFileOutFromFile/src/vsu/cs/vega/output.txt"))) {
for (int i = 0; i < matrixHeight; ++i) {
out.println(Arrays.toString(matrixForOutput[i]).replaceAll("^\\[|]$",
""));
}
}
catch (ArrayIndexOutOfBoundsException ignored){
}
//out.println(Arrays.toString(matrixForOutput).replaceAll("^\\[|]$", ""));
}
int[][] calc(int[][] array) {
int rows = array.length;
int cols = array[0].length;
boolean[] minRows = null, maxRows = null;
boolean[] minCols = null, maxCols = null;
Integer min = null;
Integer max = null;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (null == min || array[i][j] < min) {
minRows = new boolean[rows];
minRows[i] = true;
minCols = new boolean[cols];
minCols[j] = true;
min = array[i][j];
} else if (array[i][j] == min) {
minRows[i] = true;
minCols[j] = true;
}
if (null == max || array[i][j] > max) {
maxRows = new boolean[rows];
maxRows[i] = true;
maxCols = new boolean[cols];
maxCols[j] = true;
max = array[i][j];
} else if (array[i][j] == max) {
maxRows[i] = true;
maxCols[j] = true;
}
}
}
int rowsToDelete = 0, colsToDelete = 0;
for (int i = 0; i < rows; i++) {
if (minRows[i] || maxRows[i]) {
rowsToDelete++;
}
}
for (int i = 0; i < cols; i++) {
if (minCols[i] || maxCols[i]) {
colsToDelete++;
}
}
if (rows == rowsToDelete || cols == colsToDelete) {
return new int[1][0];
}
int[][] result = new int[rows - rowsToDelete][cols - colsToDelete];
for (int i = 0, r = 0; i < rows; i++) {
if (minRows[i] || maxRows[i])
continue; // пропустить строку, содержащую минимум или максимум
for (int j = 0, c = 0; j < cols; j++) {
if (minCols[j] || maxCols[j])
continue; // пропустить столбец, содержащий минимум или максимум
result[r][c++] = array[i][j];
}
r++;
}
//out.println(Arrays.toString(array).replaceAll("^\\[|]$", ""));
return result;
}
}
Your program doesn't use the "String[] args" parameter of the main method. So you don't have to provide "Program arguments". In IntelliJ in "Run Configurations" you can leave the input field empty or enter what ever you want. It doesn't make much of a difference.
However for example you could pass path names of "input.txt" and "output.txt" via program arguments instead of hard coding them in your "readMtx" method.
I am receiving this error when I submit my code. This only happens when I submit my code on an online compiler necessary for my course, however, when I run my code via InteliJ it compiles properly.
Main.java:335: error: cannot find symbol
while (!(TeamMember.contains("Stop"))){
^
symbol: method contains(String)
location: class TeamMember
1 error
<
My classes are as follows:
Main:
package com.company;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
TeamMember:
package com.company;
import java.util.ArrayList;
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
It looks like class TeamMember is not accessible from your Main class. Try this code as it should work having the classes in the same file.
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
I have to write a program that sorts names alphabetically while removing duplicates and counting the amount of times the names appear and capitalizes all of it. My partner and I have been working on this and have found no way to have the sorting method work properly and have the program find and count the times the names appear. We have to use certain methods to do this...which I linked the pdf down at the bottom. I really want to understand what's wrong and why the output is not coming out right.
public class Names {
/**
* #param args the command line arguments
*/
static ArrayList<String> fnArray = new ArrayList<String>();
static ArrayList<String> lnArray = new ArrayList<String>();
public static void main(String[] args) throws IOException {
// TODO code application logic here
getNames(fnArray, lnArray);
sort(lnArray);
find(fnArray,1);
capitalize(fnArray,lnArray);
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What file would you like to read from ?: ");
String n = kb.next();
File inputFile = new File(n);
Scanner in = new Scanner(inputFile);
while (in.hasNext()) {
String firstName = in.next();
fn.add(firstName);
String lastName = in.next();
ln.add(lastName);
}
for (int i = 0; i < fnArray.size(); i++) {
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}
public static void capitalize(ArrayList<String> fnArray, ArrayList<String> lnArray) {
String capfn = " ";
String capln = " ";
int i = 0;
int j = 0;
System.out.println("****************Names***************");
while (i < fnArray.size() && j < lnArray.size()) {
capfn = fnArray.get(i);
capln = lnArray.get(j);
String capFname = capfn.substring(0, 1).toUpperCase() + capfn.substring(1).toLowerCase();
String capLname = capln.substring(0, 1).toUpperCase() + capln.substring(1).toLowerCase();
fnArray.set(i, capFname);
lnArray.set(i, capLname);
System.out.println(lnArray.get(j) + ", " + fnArray.get(i));
i++;
j++;
}
}
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
int count = 0;
for (String str : a) {
if (str.equalsIgnoreCase(s))
count++;
}
return count; }
public static void removeDuplicates(ArrayList<String> s) {
for (int j = 0; j < s.size(); j++) {
int i = -1;
while ((i = find(s, j)) >= 0) {
s.remove(i);
}
}
}
public static void backwards(ArrayList<String> names) {
for (int i = names.size() - 1; i > 0; i--) {
names.get(i);
for (int j = 0; j < names.size(); i++) {
if ((names.get(i).equals(names.get(j)))) {
names.remove(i);
}
}
}
}
public static void sort(ArrayList<String> array) {
for (int i = 1; i < array.size(); i++) {
// find the index of the ith smallest value
int s = i - 1;
for (int j = i; j < array.size(); j++) {
if (array.get(j).compareTo(array.get(s)) < 0) {
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array.get(i - 1);
array.set(i - 1, array.get(s));
array.set(s, temp);
}
}
public static void showUnique(ArrayList<String> names){
System.out.println("Unique name list contains:");
for(int i=0 ;i< names.size() ;i++){
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}}
You can use the Collections.sort() method to sort an array list; once it is sorted, you will have entries like this:
ArrayList = { "Alpha", "Beta", "Beta", "Gamma", "Theta", "Theta" ... }
The important point to note, however, is that the duplicates will be next to each other in the sorted array.
Finally, if you want to remove duplicates, you can put all the elements of the ArrayList into a Set: set is a data-structure which removes duplicates.
Example:
Set<String> foo = new HashSet<String>( yourArrayList );
EDIT: Use this approach which is both: easy and simple-to-comprehend.
for( int i = 0; i < array.size() - 1; i++ )
{
for( int j = i + 1; j < array.size(); j++ )
{
if( array[i] > array[j] )
{
// Swap the contents of array[i] and array[j].
}
}
}
I have an input file called input.txt with a list of names. I have no problem displaying all the names and putting them in alphabetical order with both display and sort methods. But what I am currently struggling to do is create a method where I can count the recurrence of each name in the file. I would grealty appreciate if anyone could help me with this, and find a way to create this method.
public class Names {
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
for (int i = 0; i < a.size(); i = i + 1) {
String str = a.get(i);
if (str.equals(s)) {
return i;
}
}
return -1;
}
public static void capitalize(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
String name = names.get(i);
if (!name.isEmpty()) {
String firstLetter = "" + name.charAt(0);
names.set(i, firstLetter.toUpperCase() + name.substring(1).toLowerCase());
}
}
}
public static void sort(ArrayList<String> names) {
for (int i = 0; i < names.size() - 1; i = i + 1) {
int Min = i;
for (int j = i + 1; j < names.size(); j = j + 1) {
if (names.get(j).compareTo(names.get(Min)) < 0) {
Min = j;
}
}
String tmp = names.get(i);
names.set(i, names.get(Min));
names.set(Min, tmp);
}
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What is the input flie?");
String names = kb.next();
File inpFile = new File(names);
Scanner in = new Scanner(inpFile);
while (in.hasNext()) {
String firstName = in.next();
String lastName = in.next();
fn.add(firstName);
ln.add(lastName);
}
}
private int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size; i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
public static void main(String[] args) throws IOException {
ArrayList<String> first = new ArrayList<>();
ArrayList<String> last = new ArrayList<>();
getNames(first, last);
capitalize(first);
capitalize(last);
ArrayList<String> allNames = new ArrayList<>();
for (int i = 0; i < first.size(); i++) {
allNames.add(last.get(i) + ", " + first.get(i));
}
System.out.println("*******All Names******");
sort(allNames);
display(allNames);
System.out.println("*****First Name Count***");
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
System.out.println("****Last Name Count****");
sort(last);
display(last);
}
}
Use Map structure for those case:
Map<String, Integer> recurence = new HashMap<>();
int count;
for (String name : names) {
if (recurence.containsKey(name)) {
count = recurence.get(name) + 1;
} else {
count = 1;
}
recurence.put(name, count);
}
create a method that counts the occurences:
public static int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size(); i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
To use it, go through the loop in you Main ( or you can create another method)
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.