Java using scanner input a txt to a 2 dimensional array - java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class test{
public static final int SIZE = 30;
public static final int DUE_DATE = 15;
public static final int TASK_NUMBER = 30;
public static void main(String[] args)throws FileNotFoundException{
Scanner console = new Scanner(System.in);
System.out.println("Enter input file: ");
String inputCompletionName = console.next();
boolean[][] completion = new boolean[TASK_NUMBER][SIZE];
File inputCompletion = new File(inputCompletionName);
Scanner in = new Scanner(inputCompletion);
int i = 0, j = 0;
for(j = 0; j < SIZE; j++){
for(i = 0; i < TASK_NUMBER; i++){
while(in.hasNextBoolean()){
boolean input = in.nextBoolean();
completion[i][j] = input;
}
System.out.println(completion[i][j]);
}
}
}
I tried this code. My input is some boolean value but the output only have first element. Really don't know how to fix this.
My input file is just some random boolean values like this.
true
false
true
false
true
But the output only shows the first element.

The problem is this:
while(in.hasNextBoolean()) {
boolean input = in.nextBoolean();
completion[i][j] = input;
}
And that is inside your 2 for loops, so you read your booleans into the same grid cell.
This will work:
for(j = 0; j < SIZE && in.hasNextBoolean(); j++){
for(i = 0; i < TASK_NUMBER && in.hasNextBoolean(); i++){
boolean input = in.nextBoolean();
completion[i][j] = input;
System.out.println(completion[i][j]);
}
}

Related

Is there any way to fix my main class for my adjacency list graph?

So basically I'm suppose to take the numbers from a file Ex.
And turn it into this Ex.
We're suppose to make a graph class and store a adjacency list representation of a graph. We're also suppose to do it with an array of arraylists. So I got some help making the graph class and I'm making it so that the users file is processed through the graph class but for some reason there's an error and the output isn't right. Can someone help with this?
Graph Class
import java.util.ArrayList;
public class Graph {
ArrayList<Integer> [] nodes;
int n_nodes;
public Graph(int numberNodes){
this.nodes = new ArrayList[numberNodes+1];
this.n_nodes = numberNodes;
for(int i = 0; i < n_nodes + 1; i++){
nodes[i] = new ArrayList<>();
}
}
public void addNeighbor(int node, int neighbor){
nodes[node].add(neighbor);
}
public String toString(){
StringBuilder myGraph = new StringBuilder();
for(int i = 1; i < nodes.length; i++){
myGraph.append(i);
ArrayList<Integer> neighbors = nodes[i];
int totalNeighbors = neighbors.size();
for(int j = 0; j < totalNeighbors; j++){
int myneighbor = neighbors.get(j);
myGraph.append(" -> " + myneighbor);
}
myGraph.append('\n');
}
return myGraph.toString();
}}
Main Class
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws IOException {
File file = null;
JFileChooser chooser = new JFileChooser();
Scanner ans = new Scanner(System.in);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "No File Selected");
System.exit(1);
}
Scanner input = new Scanner(file);
int y = input.nextInt();
int x = 0;
Graph graph = new Graph(y);
while (input.hasNextLine()) {
for (int i = 0; i < y; i++) {
x = input.nextInt();
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}
}}
Also I'm new to the whole stackoverflow website so sorry if my wording isn't clear or my code isn't formatted good enough.
Edit
This is the error it's showing
As 3 as read by
int y = input.nextInt();
is on a different line then you need to read the CR-LF as well.
Personally I would use the following paradigm
str = input.nextLine ()
// convert to int
while (input.hasNextLine) {
str = input.nextLine ()
arr[] = str.split (" ");
// loop through length of arr - in your code `y` is not updated
add arr[x] to graph
so basically you want something like
Scanner input = new Scanner(file);
String line = input.nextLine();
int y = 0;
if (line != null) {
y = Integer.parseInt(line.trim());
}
Graph graph = new Graph(y);
while (input.hasNextLine() && y > 0) {
if (input.hasNextLine()) {
line = input.nextLine();
}
String nums[] = line.split(" ");
for (int i = 0; i < nums.length; i++) {
int x = Integer.parseInt(nums[i]);
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}

Hackerrank (Java) MAXIMUM LENGTH SUBSTRING - timeout error

Link to this problem:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
The code passes the initial test case but then times out when I go to submit on hacker rank for much larger strings. I have a feeling it's the algorithm I'm using for the unique substrings, how do I cut down this time into something efficient?
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}

Scanner throwing java.util.NoSuchElementException when input is taken

This code below throws NoSuchElementException in the function aVeryBigSum.
PS: This is task from hackerrank so I can only modify the code in function: aVeryBigSum.
This function takes the following inputs: n which is the number of elements in an array to be added, and the elements of array.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the aVeryBigSum function below.
static long aVeryBigSum(long[] ar) {
int n, sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter
= new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
long[] ar = new long[arCount];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < arCount; i++) {
long arItem = Long.parseLong(arItems[i]);
ar[i] = arItem;
}
long result = aVeryBigSum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Output:
Why are you reading from Scanner in your aVeryBigSum method?
Just loop through ar argument and calculate sum.
static long aVeryBigSum(long[] ar) {
long _sum = 0;
for(int i=0; i < ar.length; i++)
sum += ar[i];
return _sum;
}
static long aVeryBigSum(long[] ar) {
int n;
Long sum = 0;
Scanner read = new Scanner(System.in);
n = read.nextInt();
for(int i = 0; i < n; i++)
sum += read.nextLong();
return sum;
}
its working fine for me if you change: int n;
long sum=0; in existing code and try.
output:2
1 2
5
1000000001
1000000002
1000000003
1000000004
1000000005
5000000015

Morse code translator help reading from file

Okay so I know there are other Morse code answers out there, but I have looked at many, but none of them worked. For my assignment I was to read a file, Morse.txt, into parallel arrays. Instead I just made two files, Morse.txt and Alphabet.txt one with code and the other with numbers and alphabet. I am supposed to use a class I made to do the translating part and when called in main it should translate user input. I can't seem to get this working. I've tried so many things from using a toString in the class or getter, but the return is not found when I put in the loop which I think has to be there(if that makes sense)..anyway here is my code for main:
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class redo
{
public static void main(String[]args) throws IOException
{
String line2, file2 = "Morse.txt";
String line, file = "Alphabet.txt";
File openFile = new File(file);
File openFile2 = new File(file2);
Scanner inFile = new Scanner(openFile);
Scanner inFile2 = new Scanner(openFile2);
int index = 36;
char[] charArray = new char[index];
String[] code = new String[index];
for(index = 0; index < 36; index++)
{
while(inFile.hasNext())
{
line = inFile.nextLine();
charArray = line.toCharArray();
//System.out.println(charArray[index]);
}
}
for(index = 0; index < 36; index++)
{
while(inFile2.hasNext())
{
code[index] = inFile2.nextLine();
//System.out.println(code[index]);
}
}
Scanner keyboard = new Scanner(System.in);
String userInput;
System.out.println("Enter something to translate: ");
userInput= keyboard.nextLine();
Translate inputTranslate = new Translate(userInput);
inputTranslate.setInput(userInput);
inputTranslate.setAlph(charArray);
inputTranslate.setCode(code);
inFile.close();
}
}
and here is my class Translate(some things are commented out):
public class Translate
{
String input;
String code[];
char alph[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(char[] alph)
{
this.alph = alph;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
// public String getTranslate()
// {
// for(int i = 0; i < input.length(); i++)
// {
// for(int index = 0; index < alph.length; index++)
// {
// if(input.charAt(i) == alph[index])
// {
// String output = code[index];
// }
// }
// }
// return output;
// }
}
Morse.txt:
.----
..---
...--
....-
.....
-....
--...
---..
----.
.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
-.
.--.
--.-
.-.
...
..-
...-
.--
-..-
-.--
--..
Alphabet.txt:
1
2
3
4
5
6
7
8
9
0
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
The problem is your return can't reach "output", you need to declare "output" above the loops and initialise it to output = null;
Even then it'll only send one string. So I did this;
public String getTranslate()
{
String output = null;
String[] translated = new String[input.length()];
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alph.length; index++)
{
if(input.charAt(i) == alph[index])
{
output = code[index];
translated[i] = output;
}
}
}
for (int j = 1; j < translated.length; j++) {
output = translated[0].concat(translated[j]);
}
return output;
}
This basically sticks all the codes together giving you your desired outcome.

Java Anagrams reading from dictionary file

I am having trouble comparing my dictionary file to the anagrams. I put a print statement at each and it is reading in the dictionary file correctly and it is also calculating all of the anagrams correctly But it won't calculate only the anagrams from the dictionary file. I'm pretty sure it's something very minor and if someone can fix it it would greatly be appreciated.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Anagram3
{
static int size;
static int count;
static char[] charArray;
static char[] words;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("Type the path of the dictionary to read from : ");
String fileName = sc.nextLine();
List<String> dictionary = new ArrayList<String>();
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(fileName));
String word;
while((word = br.readLine())!=null)
{
dictionary.add(word);
}
}
catch(IOException e)
{
e.printStackTrace();
}
String[] words = new String[dictionary.size()];
dictionary.toArray(words);
//for( int i = 0; i < words.length; i++ )
// System.out.println(words[i]);
System.out.println("\nEnter the phrase to scramble: ");
String input = sc.nextLine();
System.out.println();
size = input.length();
count = 0;
charArray = new char[size];
for (int j = 0; j < size; j++)
charArray[j] = input.charAt(j);
doAnagram(size);
}
public static void doAnagram(int newSize)
{
int limit;
if (newSize == 1) // if too small, return;
return;
// for each position,
for (int i = 0; i < newSize; i++) {
doAnagram(newSize - 1); // anagram remaining
if (newSize == 2) // if innermost,
printAnagrams();
rotate(newSize); // rotate word
}
}
public static void rotate(int newSize)
{
int i;
int position = size - newSize;
char temp = charArray[position];
for (i = position + 1; i < size; i++)
charArray[i - 1] = charArray[i];
charArray[i - 1] = temp;
}
public static void printAnagrams()
{
for (int i = 0; i < size; i++)
{
//System.out.print(charArray[i]);
if(charArray[i] == words[i])
{
System.out.print(charArray[i]);
}
}
System.out.println();
}
}
Your static variable words is not being used because you define a new String[] words before the assignment.
Use the equals method to compare Strings. 1
Another issue is that you're comparing the i'th anagram generated to the i'th element in your dictionary, when you actually (presumably) want to test if the i'th anagram is present in the dictionary at any position.
You can try using a HashSet h of strings, rather than the array, for the dictionary, and then check for validity of an anagram with h.contains(...).

Categories

Resources