What should be entered in intellij IDEA command line arguments? - java

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.

Related

Why else statement is executing although if statement is true?

import java.util.Scanner;
class candidate {
public String name;
public int count;
public candidate(String name) {
super();
this.name = name;
}
}
public class DayScholar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
candidate[] candidates = new candidate[3];
candidates[0] = new candidate("vikas");
candidates[1] = new candidate("ganesh");
candidates[2] = new candidate("teja");
System.out.print("No. of voters : ");
int voters = in.nextInt();
in.nextLine();
for (int i = 0; i < voters; i++) {
System.out.print("vote : ");
String name = in.nextLine().toLowerCase();
for (int j = 0; j < 3; j++) {
Here is the code, although if the statement is true else is also executing. How to check the condition
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else { **//problem here**
System.out.println("N");
break;
}
}
}
int highest = 0;
String winner = "";
for (int i = 0; i < 3; i++) {
if (candidates[i].count > highest) {
highest = candidates[i].count;
winner = candidates[i].name;
} else if (candidates[i].count == highest) {
winner += ("\n" + candidates[i].name);
}
}
System.out.println(winner);
}
}
Assuming the user enters a valid name, the following loop will increment the count field on the candidate with the matching name, and print N for the other 2 candidates.
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
candidates[j].count++;
} else {
System.out.println("N");
break;
}
}
To fix, you need the loop to just set the index of the matching candidate, then do the increment or printing after the loop:
int matchingIndex = -1; // -1 = not found
for (int j = 0; j < 3; j++) {
if (name.equals(candidates[j].name)) {
matchingIndex = j;
break;
}
}
if (matchingIndex == -1) {
System.out.println("N");
} else {
candidates[matchingIndex].count++;
}

Taking input to a Java or C program from a web page?

I was implementing traveling salesman optimisation problem and i programmed the same using Java and C program. The program takes matrix as a input and displays the optimal path.
Java Code
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class TSPNearestNeighbour {
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbour() {
stack = new Stack<Integer>();
}
public void tsp(int adjacencyMatrix[][]) {
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new
int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty()) {
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes) {
if
(adjacencyMatrix[element][i] > 1 && visited[i] == 0) {
if (min > adjacencyMatrix[element][i]) {
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag) {
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
}
public static void main(String... arg) {
int number_of_nodes;
Scanner scanner = null;
try {
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if
(adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) {
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
scanner.close();
}
}
C Code
#include<stdio.h>
#include<conio.h>
int a[10][10],visited[10],n,cost=0;
void get()
{
int i,j;
printf("Enter No. of Cities: ");
scanf("%d",&n);
printf("\nEnter Cost Matrix\n");
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row # : %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&a[i][j]);
visited[i]=0;
}
printf("\n\nThe cost list is:\n\n");
for( i=0;i < n;i++)
{
printf("\n\n");
for(j=0;j < n;j++)
printf("\t%d",a[i][j]);
}
}
void mincost(int city)
{
int i,ncity;
visited[city]=1;
printf("%d -->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i] < min)
{
min=a[i][c]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
void put()
{
printf("\n\nMinimum cost:");
printf("%d",cost);
}
void main()
{
clrscr();
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
getch();
}
The two programs are also working fine. But i want to implement a case study for it and i need to take input for those matrix from a webpage. So is there any way to do it so? For java or for c, either of one is fine. I know JSP and Web Programming too. I just want to how to take the input for those matrix and send it to server side.
For Java i used Jsp and Servlets.
Index.jsp
<body>
<form action="sample" method="post">
<h1>Travelling Salesman Problem</h1>
<input placeholder="Number of Cities" type="text" name="cities" required="">
<input placeholder="Matrix" type="text" name="matrix" required="">
<button>Submit</button>
</form>
</body>
Servlet Sample.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
import static java.lang.System.out;
public class sample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String city = request.getParameter("cities");
String numbers = request.getParameter("matrix");
int[] abc=new int[100];
String[] args = new String[2];
args[0] = city;
args[1] = numbers;
abc = TSPNearestNeighbour.main(args); //passing the two arguments to my java class
PrintWriter out = response.getWriter();
for (int i=0;i<=abc.length;i++) {
out.println(abc[i]);
}
}
}
TSPNearestNeighbour.Java (Java Class)
import java.util.InputMismatchException;
import java.util.Stack;
public class TSPNearestNeighbour
{
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
public int[] tsp(int[][] adjacencyMatrix)
{
int[] arr= new int[100];
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new
int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if
(adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print(dst +"\t");
minFlag = false;
continue;
}
stack.pop();
}
return arr;// ignore this line,it's regarding my logic
}
public static int[] main (String[] args) {
if (args.length < 2) {
System.out.println("Two arguments required <city> <numbers>");
System.exit(-1);
}
int number_of_nodes;
number_of_nodes = Integer.parseInt(args[0]);
String[] splitText = args[1].split(" +");
int[] mat = new int[splitText.length];
for (int i = 0; i < splitText.length; i++) {
mat[i] = Integer.parseInt(splitText[i]); // since we are passing the parameters to matrix,we convert every value from string type to integer
}
int[] abc = new int[100];
try {
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
int count = 0;
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if (count == mat.length)
break;
adjacency_matrix[i][j] = mat[(i - 1) * number_of_nodes + (j - 1)];//matrix input
count++;
}
}
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) {
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
abc = tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
return abc;
}
}

save contents from void method to variable

I am trying to print write the contents from void method to a file but I cant seem to get it to work. I call my method in the main and it prints to the console just fine. I have tried many different approaches but not one worked. Can anyone help/guide me in the right direction?
I have pasted my code below for reference. In my main function I call dijkstra(M, SV - 1) that prints my array to the screen, my goal is to have that same array printed to a file.
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;
public class Main_2 {
static int SV = 0; // source vertex
static int N = 0;
static int M[][];
public static int distance[];
static int minDistance(int dist[], Boolean shortestPath[]) {
int min = Integer.MAX_VALUE, minI = -1;
for (int i = 0; i < N; i++)
if (shortestPath[i] == false && dist[i] <= min) {
min = dist[i];
minI = i;
}
return minI;
}
public static void printArr(int dist[], int n) {
// System.out.println("vertex distance");
for (int i = 0; i < N; i++)
System.out.println("[" + dist[i] + "]");
}
public static void dijkstra(int graph[][], int src) {
// The output array. dist[i] will hold
// the shortest distance from src to i
int dist[] = new int[N];
// sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
Boolean shortestPath[] = new Boolean[N];
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < N; i++) {
dist[i] = Integer.MAX_VALUE;
shortestPath[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int i = 0; i < N - 1; i++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, shortestPath);
// Mark the picked vertex as processed
shortestPath[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int j = 0; j < N; j++)
// Update dist[v] only if is not in sptSet, there is an
// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!shortestPath[j] && graph[u][j] != 0 && dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][j] < dist[j])
dist[j] = dist[u] + graph[u][j];
}
// print the constructed distance array
printArr(dist, N);
}
public static void main(String[] args) {
try {
int i = 0, j = 0; // counters
FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt"); // name of input file must go in here
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1);
try {
FileWriter fw = new FileWriter("Shortest_path.txt"); // writes transitive closure to file
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < N; i++) {
// bw.write(dist[i]);
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void printMatrix(int[][] Matrix) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(Matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}
try (FileWriter fileWriter = new FileWriter("YourFileName.txt");
PrintWriter printWriter = new PrintWriter(fileWriter)) {
for (int i=0; i<N; i++) {
printWriter.printf(Integer.toString(dist[i]));
}
} catch (Exception e) {
System.out.println(e);
}
"A" simple solution, would be to pass the PrintStream you want to use to the method, for example...
public static void printArr(int dist[], int n, PrintStream ps) {
for (int i = 0; i < N; i++) {
ps.println("[" + dist[i] + "]");
}
}
This will then require you to pass a PrintStream instance to the method when ever you call it. Since dijkstra also calls printArr, you will need to pass the instance of the PrintStream to it as well...
public static void dijkstra(int graph[][], int src, PrintStream ps) {
//...
// print the constructed distance array
printArr(dist, N, ps);
}
Then you just create an instance of the PrintStream you want to use and pass it to the methods...
public static void main(String[] args) {
try (FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt")) {
int i = 0, j = 0; // counters
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
try (PrintStream ps = new PrintStream("EXAMPLE(2).txt")) {
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1, ps);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I restructured your main method slightly, as the output is depended on the success of the input ;). Also see The try-with-resources statement for more details
This means you could do something like...
dijkstra(M, SV - 1, System.out);
and it would once again print the output to the console :)

RuntimeException: Uncompilable source code

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.

How can I avoid repetition of the same number?

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.

Categories