CS106A handout 6 Exception java.lang.NullPointerException - java

Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}

I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}

Related

Trying Linear Search in java but it seems loop is not iterating

I am trying to use Linear Search using java to find the name in the 2d array and print the details related to it, but the code is directly going to last loop without searching
the code is
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Source {
String customerDetails[][]=new String[5][3];
Source()
{
customerDetails[0][0]="1001";
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chennai";
customerDetails[1][0]="1008";
customerDetails[1][1]="Akshay";
customerDetails[1][0]="Pune";
customerDetails[2][0]="1002";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="1204";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="1005";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
}
public static void main(String args[] ) throws Exception {
Source nc = new Source();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
if(nc.customerDetails[i][j].equals(key)){
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
if(!found){
System.out.println("No Record Found");
break;
}
}
}
}
i want to find Gaurav in the array and print
1204
Gaurav
Delhi
public class test
{
String customerDetails[][] = new String[5][3];
test()
{
customerDetails[0][0] = "1001";
customerDetails[0][1] = "Raj";
customerDetails[0][2] = "Chennai";
customerDetails[1][0] = "1008";
customerDetails[1][1] = "Akshay";
customerDetails[1][2] = "Pune";
customerDetails[2][0] = "1002";
customerDetails[2][1] = "Simrath";
customerDetails[2][2] = "Amristar";
customerDetails[3][0] = "1204";
customerDetails[3][1] = "Gaurav";
customerDetails[3][2] = "Delhi";
customerDetails[4][0] = "1005";
customerDetails[4][1] = "Ganesh";
customerDetails[4][2] = "Chennai";
}
public static void main(String args[]) throws Exception
{
test nc = new test();
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
boolean found = false;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
if (nc.customerDetails[i][j].equals(key))
{
found = true;
System.out.println(nc.customerDetails[i][0] + '\n' + nc.customerDetails[i][1] + '\n' + nc.customerDetails[i][2]);
break;
}
}
}
if (!found)
{
System.out.println("No Record Found");
// break;
}
}
}
This should work. if(!found) should be outside the loop to check all records.

Timed Out and NZEC on CodeChef Problem NUKES

While trying out the problem "Nuclear Reactors" , i'm getting the results on my computer ,but in CodeChef there is a timelimit of 0.2 secs and while submitting my answer i'm getting a TLE(time limit exceeded) error and in one test i'm getting wrong answer.
I don't have a clue what is causing this.
Any hints would be helpful.
Link :https://www.codechef.com/problems/NUKES
My code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) {
FastReader fr = new FastReader();
// I/P
int a = fr.nextInt();
int n = fr.nextInt();
int k = fr.nextInt();
// ARRAY TO STORE RESULT
int react[] = new int[k];
// ARRAY OF ZERO AND ONES
int temp_one[]=new int[k];
int temp_zero[]=new int[k];
for (int i = 0; i < k; i++){
react[i] = 0;
temp_zero[i]=react[i];
temp_one[i]=1;
}
while (a != 0) { // TO REPEAT TILL ALL (A) ARE USED
int j = 0;
while(react[j]>=n){ // CHECK(value in K>=A)
react[j] = 0;
j++;
}
react[j]++;
if(Arrays.equals(react,temp_one)){ // CHECK(all K are filled)
react=temp_zero;
}
a--;
}
for(int i=0;i<k;i++){
System.out.print(react[i]+" ");
}
}
//////////////////// FAST IO //////////////////////
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Results given by CodeChef
This code should work for your algorithm.
int[] ret = new int[k];
for(int i = (int)(Math.log(a)/Math.log(n+1)); i >= 0; i--) {
int val = (int)(a/Math.pow(n+1,i));
a -= val*Math.pow(n+1,i);
if (i < k) ret[i] = val;
}
ret is your return array.
It basically finds the base n+1 representation of a, which is the answer they want you to get. If you want more information on why it works, feel free to ask!

Finding largest value in an array from a text file

I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}

How to randomly choose a word from text and also reverse the same word when chosen

I would like to choose a word from a text file. Print that word and also print the same word in reverse. When I run the code, I have the output below. I just need to print the same word in reverse. But when I call the reverse method in the main function nothing prints.
Below is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class SortingInput {
private static Scanner file;
private static ArrayList<String> words = new ArrayList<String>();
private static void openFile(){
try {
file = new Scanner(new File("word-file.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("IOEXCEPION");
}
}
public void closeFile(){
file.close();
}
private static void randomFile() {
Random r = new Random();
while(file.hasNextLine()){
words.add(file.nextLine());
}
String randomWord = words.get(r.nextInt(words.size()));
Collections.shuffle(words);
System.out.println(randomWord);
}
private static void reverse(ArrayList<String> array){
for(int i = 0; i < array.size(); i++) {
String element = array.get(i);
String setter = " ";
for(int k = 0; k < element.length(); k++){
char temp = element.charAt(element.length()- k - 1);
setter += temp;
}
array.set(i, setter);
}
}
public static void main(String[] args) {
openFile();
System.out.print("Before: ");
randomFile();
System.out.print("After: ");
reverse(words);**
}
}
You don't need to reverse the whole ArrayList of strings.
Remove private static void reverse(ArrayList<String> array) method, make randomFile()return a String which will be reversed. StringBuffer and StringBuilder classes have this reverse() method for reversing strings.
I also suggest you rename randomFile() to randomWord() since you're randomizing words not files.
randomWord():
private static String randomWord() {
Random r = new Random();
while(file.hasNextLine()){
words.add(file.nextLine());
}
String randomWord = words.get(r.nextInt(words.size()));
// Collections.shuffle(words); -> this is not needed since randomWord is already produced.
return randomWord;
}
main():
public static void main(String[] args) {
openFile();
String random = randomWord();
System.out.println("Before: " + random);
System.out.print("After: " + new StringBuilder(random).reverse() );
}
Sample output:
Before: hallow
After: wollah
The code would be much shorter if you use FileUtils from Apache Common IO and StringBuilder. An example is:
public static void main( String[] args )
{
File file = new File( "word-file.txt" );
try
{
List<String> lines = FileUtils.readLines( file );
Random random=new Random();
String before=lines.get(random.nextInt(lines.size()));
System.out.println("Before:"+before);
System.out.println("After:"+ new StringBuilder(before).reverse());
}
catch( IOException e )
{
e.printStackTrace();
}
}

Can some one help me with this message java Exception?

i have an assignment in java to sort numbers in ascending order and find the max, min , mean and standard deviation
i have done that already but i wanted to change the program to work with double values but there is an exception showing and i cant solve the problem please help can someone fix it.
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class FileJava2 {
static double min,max,sum,k;
static double PS1,PS2;
static double stdev=0;
static double aa, x[]=new double[1000], no;
static String source= "",source2= "";
public static void main (String args[]) throws Exception
{
FileJava2.fileinput();
FileJava2.fileoutput();
FileJava2.sort();
FileJava2.display();
}
public static void sort() throws Exception
{
sum=0;
for(int j=0;j<k;j++){
sum+=x[j];
System.out.print(x[j]+" ");
}
double t;
for(int dd=0; dd<k; dd++){
for(int in=0;in<k-1;in++){
if(x[dd]<x[in])
{t=x[dd];
x[dd]=x[in];
x[in]=t;
}
}
}
min=x[0];max=0;
System.out.print("\nSorted Elements: ");
for(int j=0;j<k;j++){
if(x[j]<min)
min=x[j];
if(x[j]>max)
max=x[j];
source2+=x[j];
System.out.print(x[j]+" ");
source+=x[j];
}
PS1=0;PS2=0;
for( int i=0; i<k;i++) {
PS1 += x[i];
PS2 += Math.pow(x[i], 2);
stdev = Math.sqrt(i*PS2 - Math.pow(PS1, 2))/i;
}
byte buf1[]=source2.getBytes();
OutputStream fo1=new FileOutputStream("SortData.txt");
for (int i=0;i<buf1.length;i++)
{
fo1.write(buf1[i]);
}
}
public static void fileinput() throws Exception{
Scanner s = new Scanner(System.in);
do{
System.out.print("Enter Numbers: ");
aa=s.nextDouble();
if(aa==0)
break;
else
source+=(aa+" ");
} while(aa!=0);
System.out.println("YOUR INPUT: "+source);
k=0;
byte buf[]=source.getBytes();
OutputStream fo=new FileOutputStream("waitingtime");
for (int i=0;i<buf.length;i++)
{
fo.write(buf[i]);
}
System.out.println("\nElements successfuly saved into waitingtime.dat ");
}
public static void fileoutput() throws Exception{
BufferedReader inputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("waitingtime"));
String l;
while ((l = inputStream.readLine()) != null) {
// System.out.println(l);
for ( int i = 0; i < l.length(); i++ ) {
String cc=" "+l.charAt( i );
x[(int)k++]=Integer.parseInt(cc);
// System.out.println(no);
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public static void display(){
System.out.println("\nElements successfuly saved into SortData.dat ");
System.out.print("\nMinimum: "+min);
System.out.print("\nMaximun:"+max);
System.out.print("\nMean:"+sum/k);
System.out.print("\nMidrange:"+(min+max)/2);
System.out.println("\nStandard Deviation:"+stdev);
}
}
and the exception message
Enter Numbers: 1
Enter Numbers: 1
Enter Numbers: 2
Enter Numbers: 5
Enter Numbers: 0
YOUR INPUT: 1.0 1.0 2.0 5.0
Elements successfuly saved into waitingtime.dat
Exception in thread "main" java.lang.NumberFormatException: For input string: "."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at FileJava2.fileoutput(FileJava2.java:110)
at FileJava2.main(FileJava2.java:21)
and can someone tell me why when i enter 1 it shows 1.0?
Replace this on your for loop of fileoutput() method
for (int i = 0; i < l.length(); i++) {
if (l.charAt(i) != '.' && l.charAt(i) != ' ') {
String cc = (" " + l.charAt(i)).trim();
int result = Integer.parseInt(cc);
if (result != 0) {
x[(int) k++] = result;
}
}
}
You are trying to parse each individual character in the string to an integer. After reading the line "1.0 1.0 2.0 5.0" you need to split the numbers and pass the substrings to parse int/double. You can split using the triple whitespace characters like so:
while ((l = inputStream.readLine()) != null) {
for(String ss:l.split(" ") {
x[(int)k++] = Double.parseDouble(ss);
}
}
This exception:
java.lang.NumberFormatException: For input string: "."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
Tells you that you that the String . could not be parsed to an int.
And makes sense, because what int could be represented by . ?
import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class FileJava2 {
static double min,max,sum,k;
static double PS1,PS2;
static double stdev=0;
static double aa, x[]=new double[1000], no;
static String source= "",source2= "";
public static void main (String args[]) throws Exception
{
FileJava2.fileinput();
FileJava2.fileoutput();
FileJava2.sort();
FileJava2.display();
}
public static void sort() throws Exception
{
sum=0;
for(int j=0;j<k;j++){
sum+=x[j];
System.out.print(x[j]+" ");
}
double t;
for(int dd=0; dd<k; dd++){
for(int in=0;in<k-1;in++){
if(x[dd]<x[in])
{t=x[dd];
x[dd]=x[in];
x[in]=t;
}
}
}
min=x[0];max=0;
System.out.print("\nSorted Elements: ");
for(int j=0;j<k;j++){
if(x[j]<min)
min=x[j];
if(x[j]>max)
max=x[j];
source2+=x[j];
System.out.print(x[j]+" ");
source+=x[j];
}
PS1=0;PS2=0;
for( int i=0; i<k;i++) {
PS1 += x[i];
PS2 += Math.pow(x[i], 2);
stdev = Math.sqrt(i*PS2 - Math.pow(PS1, 2))/i;
}
byte buf1[]=source2.getBytes();
OutputStream fo1=new FileOutputStream("SortData.txt");
for (int i=0;i<buf1.length;i++)
{
fo1.write(buf1[i]);
}
}
public static void fileinput() throws Exception{
Scanner s = new Scanner(System.in);
do{
System.out.print("Enter Numbers: ");
aa=s.nextDouble();
if(aa==0)
break;
else
source+=(aa+" ");
} while(aa!=0);
System.out.println("YOUR INPUT: "+source);
k=0;
byte buf[]=source.getBytes();
OutputStream fo=new FileOutputStream("waitingtime");
for (int i=0;i<buf.length;i++)
{
fo.write(buf[i]);
}
System.out.println("\nElements successfuly saved into waitingtime.dat ");
}
public static void fileoutput() throws Exception{
BufferedReader inputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("waitingtime"));
String l;
while ((l = inputStream.readLine()) != null) {
// System.out.println(l);
String numbers[] = l.split(" ");
for (String cc : numbers) {
x[(int)k++]=Double.parseDouble(cc);
// System.out.println(no);
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public static void display(){
System.out.println("\nElements successfuly saved into SortData.dat ");
System.out.print("\nMinimum: "+min);
System.out.print("\nMaximun:"+max);
System.out.print("\nMean:"+sum/k);
System.out.print("\nMidrange:"+(min+max)/2);
System.out.println("\nStandard Deviation:"+stdev);
}
}
Your FileJava2.output() has been changed solve your issue. Using split to get values then converting string to double instead of int.

Categories

Resources