My code needs to stop printing when the text in the file runs out. Right now it prints out null until it hits 100. My assignment wants it to stop taking in when there is nothing else to print.
import java.io.*;
import java.util.Scanner;
public class TextFileReader {
String[] stringArray = new String [100];
TextFileReader() {
}
TextFileReader(String fileName) {
try {
FileInputStream fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
for(int i = 0; i < stringArray.length || scan.hasNextLine(); i++) {
if(scan.hasNextLine()){
stringArray[i] = scan.nextLine();
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
public String contents(String fileName) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
}
return sb.toString();
}
public void display(String fileName) {
for(int i = 0; i < stringArray.length; i++) {
System.out.println(i + ": " + stringArray[i]);
}
}
}
}
Your problem is not that you are reading wrongly it is that you are displaying wrong. You initialize stringArray = new String [100]; meaning that it will have 100 nulls at the beginning. And after you are done reading if you read less than 100 lines you will still have nulls when you call display(String fileName)
Solution is to stop displaying when you reach empty indexes
public void display(String fileName) {
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == null) break;
System.out.println(i + ": " + stringArray[i]);
}
}
}
It runs for 100 iterations because the array has 100 as size
Try something like inserting this code in a while loop where you read the lines this:
if (stringArray[i]==null) break
I would also sugest saving the lines read to a list, because this one you don't need to ghave limited to a size
This solution is better because you are reading for more iterations than you are required, the number of iterations in you're array does not match the number of lines in your file
I'm trying to read a large text file of about 7516 lines of text. When I read a smaller file (9 lines) the program works fine. But with the large file it seems to get caught in something and just keeps running without anything actually happening.I'm not sure where to start looking for the issue.
The code reads a text file and then turn it into an array. Then it passes the array into a shuffle and writes it into another text file. Or at least that's what I want it to do.
package Rn1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Read2 {
static void randomShuffle( int arr[], int n)
{
// Creating a object for Random class
Random r = new Random();
// Start from the last element and swap one by one. We don't
// need to run for the first element that's why i > 0
for (int i = n-1; i > 0; i--) {
// Pick a random index from 0 to i
int j = r.nextInt(i+1);
// Swap arr[i] with the element at random index
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Prints the random array
System.out.println(Arrays.toString(arr));
}
public static String readString(String file) {
String text = "";
try {
Scanner s = new Scanner(new File(file));
while(s.hasNext()) {
text = text + s.next() + " ";
}
}
catch(FileNotFoundException e) {
System.out.println("Not Found");
}
return text;
}
public static String[] readArray(String file) {
//Step 1:
//Count how many elements in the file (lines)
//Step 2
//Create array
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr +1;
if (s1.hasNext()) {
s1.next();
}
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for(int i = 0; i < ctr; i = i+1){
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e) {
}
return null;
}
public static void main(String[] args) throws Exception
{
//String text = readString("C:\\Users\\herna\\Desktop\\Test.txt");
//System.out.println(text);
String[] words = readArray("C:\\Users\\herna\\Desktop\\ErdosCA.txt");
int n = words.length;
int [] arr = new int [n];
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for (int i=0; i < words.length; i = i + 1 )
{
arr[i] = Integer.parseInt(words[i]);
//writer.println(words[i]);
}
//System.out.println(Arrays.toString(arr));
randomShuffle(arr, n);
writer.println(Arrays.toString(arr));
//writer.println(Arrays.toString(words));
//writer.println("Update*");
writer.close();
}
}
The program is also reproducable with small files, for example:
1
2
3
The program enters an endless loop when the last line of the file is empty. The bad part is this:
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr + 1;
if (s1.hasNext())
{
s1.next();
}
}
If you are before the empty line, then s1.hasNextLine() is true but s1.hasNext() is false. So you do not read the next element. Then in the next iteration of the loop, s1.hasNextLine() is still true, and thus the loop does never end.
By the way, you should never catch Exceptions without handling them. You should at least output an error message and then call e.printStackTrace().
Using ReadInputCSVFromFile method to read the sample CSV from file and parse it to a String array after using split(",") function and pass it to a 2D array to read it fully.
PrintResultsForTesting method would be only for printing out the 2D array for visual overlook.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class CSVReader {
public static String[][] readIntoArray;
public static String[][] myArray;
public static String[][] csvResults;
public static int countRow = 0;
public static int countColumn = 0;
public static void main(String[] args) {
csvResults = ReadInputCSVFromFile(myArray);
PrintResultsForTesting(csvResults);
}
public static void PrintResultsForTesting(String[][] csvResults) {
String[][] newMyArray = new String[myArray.length][myArray[0].length];
for (int i = 0; i < csvResults.length; ++i) {
for (int j = 0; j < csvResults[0].length; ++j) {
System.out.println(csvResults[i][j]);
}
}
}
public static String[][] ReadInputCSVFromFile(String[][] myArray) {
countRow = 0;
countColumn = 0;
Scanner scanner;
String inputLine;
String fileLocation;
fileLocation = "D://WorkSpace_Git//methods//iq-distribution//docs/SAP.csv";
try {
scanner = new Scanner(new BufferedReader(new FileReader(fileLocation)));
while (scanner.hasNext()) {
inputLine = scanner.nextLine();
String[] readIntoArray = inputLine.split(",");
// count rows and columns
++countRow;
countColumn = readIntoArray.length;
myArray = new String[countRow][countColumn];
}
for (int i = 0; i < countRow; ++i) {
for (int j = 0; j < countColumn; ++j) {
myArray[i][j] = readIntoArray[i][j];
}
}
System.out.println("Rows: " + countRow + '\n' + "Columns: " + countColumn);
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return myArray;
}
}
The error is:
Exception in thread "main" java.lang.NullPointerException at project.CSVReader.ReadInputCSVFromFile(CSVReader.java:52) at project.CSVReader.main(CSVReader.java:16) Process finished with exit code 1
After looking briefly at your code, I could spot a bug. When this method is called:
public static String[][] ReadInputCSVFromFile(String[][] myArray) {
myArray is null.
If you want to write to the array, you will need to instantiate the array first.
If you are using arrays actually you should know in advance its dimensions. If you do not know it, consider using some implementation of java.util.List - like java.util.ArrayList.
Another problem is exception handling. If the file is not found, then the exception is caught and you still call this method PrintResultsForTesting with unpredicatable results. Better to use a throws clause and stop the execution alltogether. So instead of the try catch in method ReadInputCSVFromFile just use a throws FileNotFoundException in this method.
When I run the program, it prints out "After trim, wordList length: 0". Not sure why?
import java.io.*;
import java.util.*;
public class Project5 {
static final int INITIAL_CAPACITY = 10;
public static void main(String[] args) throws Exception {
if (args.length < 1)
die("You must type the dictionary filename on cmd line.\n");
// Here we have declared an int array, called 'histogram' with initial
// capacity of 0
// it is a freq counter to word lengths in the file
int[] histogram = new int[0];
// Here we have declared an array of String to read the dictionary file
// into. We use BufferedReader (not Scanner).
// With each word read in, examine it's length and update word length
// frequency histogram accordingly
String[] wordList = new String[INITIAL_CAPACITY];
int wordCount = 0;
BufferedReader infile = new BufferedReader(new FileReader(args[0]));
while (infile.ready()) // i.e. while there are more lines of text in the
// file
{
String word = infile.readLine();
// YOUR CODE HERE TO CHECK TO SEE IF WORDLIST IS FULL
// IF SO YOU MUST DO AN UPSIZE JUST LIKE LAB#6
if (word.length() >= histogram.length)
histogram = upSizeHisto(histogram, word.length() + 1);
// YOUR CODE HERE to add this word to your list
histogram[word.length()]++;
// YOUR CODE HERE TO LOOK AT THE LENGTH OF THE WORD AND UPDATE
// HISTOGRAM
// example if word.length() is 5 then histogram[5] gets increment
// BUT IF WORD LENGTH IS >= HISTORGRAM LENGTH
// THEN YOU NEED TO FIRST CALL upSizeHisto TO UPSIZE THE HISTOGRAM
// TO BE OF EXACTLY LENGTH word.length()+1
// SIMILAR TO HOW YOU HAD TO UPSIZE WORDLIST
} // END WHILE INFILE READY
infile.close();
wordList = trimArr(wordList, wordCount);
System.out.println("After trim, wordList length: " + wordList.length);
// PRINT WORD LENGTH FREQ HISTOGRAM
for (int i = 0; i < histogram.length; i++)
System.out.println("words of length " + i + ": " + histogram[i]);
} // END main
private static void die(String msg) {
System.out.println(msg);
System.exit(0);
}
private static String[] upSizeArr(String[] oldArr) {
int i = 0;
String[] newArr = new String[oldArr.length * 2];
for (i = 0; i < oldArr.length; i++) {
newArr[i] = oldArr[i];
}
return newArr; // replace with code from Lab6
}
private static String[] trimArr(String[] oldArr, int count) {
int i = 0;
String[] trimArr = new String[count];
for (i = 0; i < trimArr.length; i++) {
trimArr[i] = oldArr[i];
}
return trimArr; // replace with code from Lab6
}
private static int[] upSizeHisto(int[] oldArr, int newLength) {
int i = 0;
int upSizeHisto[] = new int[newLength];
for (i = 0; i < oldArr.length; i++) {
upSizeHisto[i] = oldArr[i];
}
return upSizeHisto; // change all this to upsize the int[] array
}
} // END CLASS PROJECT#5
Your code is working perfectly, the only problem is that you never increment wordCount or add your word to wordList. Just add this somewhere inside your while loop and you're good to go:
if (wordCount >= wordList.length) wordList = upSizeArr(wordList);
wordList[wordCount] = word;
wordCount++;
In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}