My Java Program won't Compile - java

As I just stated above this program won't compile. In my IDE, TextPad, it gives me 2 errors in the createArray method. It says that both a right bracket and semicolon are expected in my return statement when I indeed have them there. Could someone help me out here?
public class Driver
{
private static int size;
private static String somePromptMessage;
private static boolean validInput;
private static String userData;
public static void main(String[] args) throws IOException
{
validInput = false;
BufferedReader keyboard;
keyboard = new BufferedReader(new InputStreamReader(System.in));
int result;
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
{
return result;
}
}
public static void print(int[]x)
{
System.out.println("The array contains" + size + "elements");
for(int i = 0; i<x.length; i++)
{
System.out.println(x[i]);
}
}
private static int[] createArray(int size)
{
return int[size];
}

You're missing the enclosing } for the class, but I'll assume that one is a copy-paste issue.
The actual problem I see is that you want
return new int[size];
instead of
return int[size];
in your createArray function.

I see an extra simi-colon here:
while(!validInput);
{
return result;
}
Update: It was brought to my attention that this is actually a do while so why the extra braces around the return statement?

remove braces after while across return result; as it is do-while:
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
return result;

Related

Merge strings of ints

I am stuck ... can anyone tell me how can i do this:
Here is the required input and output:
input: [4, 2, +, 8, +, 2, 5, multiply sign, 2]
output: [42,+,8,+,25,multiply sign,2]
This was my last try and it output nothing :
public static List<String> unifyNumbers(List<String> data) {
List<String> temp = new ArrayList<String>();
for (int i = 0; i < data.size(); i++) {
String num = "";
try {
num += Integer.parseInt(data.get(i));
for (int i2 = i; i < data.size(); i++) {
try {
num += Integer.parseInt(data.get(i2));
} catch (NumberFormatException e) {
e.printStackTrace();
i = i2 - 1;
temp.add(num);
num = "";
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
temp.add(data.get(i));
}
}
return temp;
}
The i2 variable doesn't iterate, which is why you are not getting any output. That loop isn't necessary anyway. Putting the test to see if a string is a number in its own function simplifies things a little.
Here is a revised solution, and a link to a place you can test it.
http://tpcg.io/l2xbRASM
public static Boolean isNumeric(String value) {
try {
Integer.parseInt(value);
return true;
} catch(NumberFormatException e) {
return false;
}
}
public static List<String> unifyNumbers(List<String> data) {
List<String> temp = new ArrayList<String>();
String num = "";
for (int i = 0; i < data.size(); i++) {
// HelloWorld is the name of the class I am testing this in.
if(HelloWorld.isNumeric(data.get(i))) {
num += Integer.parseInt(data.get(i));
} else {
temp.add(num);
// this line adds the arithmetic operator to the resulting output
temp.add(data.get(i));
num = "";
}
}
// add number that remains to the array
if(num != "")
temp.add(num);
return temp;
}
I hope this adds to the answers other people have given.
import java.util.*;
import java.lang.*;
import java.io.*;
class Sample
{
public static void main (String[] args) throws java.lang.Exception
{
List<String> sampleData = new ArrayList<String>();
sampleData.add("1");
sampleData.add("2");
sampleData.add("*");
sampleData.add("8");
sampleData.add("+");
sampleData.add("2");
sampleData.add("5");
List<String> resultList = unifyNumbers(sampleData);
System.out.println(resultList);
}
public static List<String> unifyNumbers(List<String> data) {
String concatedNum = "";
List<String> resultList = new ArrayList<String>();
for(String arrVal: data) {
if(isInteger(arrVal)) {
concatedNum += arrVal;
} else {
resultList.add(concatedNum);
resultList.add(arrVal);
concatedNum = "";
}
}
if(!concatedNum.isEmpty()) {
resultList.add(concatedNum);
}
return resultList;
}
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
}
It seems like Gowtham Nagarajan already gave you a better way to do it. I'd advise you to use a modified version of his code, one that checks whether your String is an Integer without a try/catch block (see this question for a discussion on why your current approach isn't really good practice).
I'll still show you what I did, just to help you understand what went wrong with your first approch and how to fix something like that.
I changed your code to make it work like you want it to. All my check prints that I used to find problems are still in there, to give you an idea how to find problems in the execution. Checks like these make it easier to follow the "flow" of your program and to find out what went wrong. You can take a piece of paper and write down every step your program goes through, the checks will show you if everything works like you want it to or if there's unwanted behavior.
public static List<String> unifyNumbers(List<String> data) {
List<String> temp = new ArrayList<String>();
for (int i = 0; i < data.size(); i++) {
String num = "";
try {
num = "" + Integer.parseInt(data.get(i));
System.out.println("Check 1");
for (int i2 = i + 1; i2 < data.size(); i2++) {
try {
num += Integer.parseInt(data.get(i2));
System.out.println("Check 2");
} catch (NumberFormatException e) {
System.out.println("Error inside loop");
e.printStackTrace();
i = i2 - 1;
System.out.println("To add:" + num);
temp.add(num);
num = "";
break;
}
}
} catch (NumberFormatException e) {
System.out.println("Error outside loop");
e.printStackTrace();
temp.add(data.get(i));
}
if (!num.equals("")) {
System.out.println(num);
temp.add(num);
}
}
return temp;
}
When using the print statements, I found out that your original code never left the first inside loop. The print statement at the end System.out.println(num); printed something like 44444444. Hints like this one can help you make the code work.
There were a lot of small mistakes that were reasonably easy to find this way. I suggest you try that next time. Good Luck!

How to parse a form of csv file in java

I am trying to parse a rather special-formatted file by using scanner with delimiter, but I am rather new to regex. The format:
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER",...
Currently, I am using this delimiter and code below:
static void readNames(String[] names) {
try {
Scanner sc = new Scanner(new File("names.txt")).useDelimiter(",");
int count = 0;
while(sc.hasNext()) {
names[count] = sc.next();
count ++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
However, this gives me quotes around the String which is not what I want.
Then, I tried to the following delimiter:
String delimiter = " "," ";
Which I quickly realised is not recognised as a String due to the amount of quotation marks.
This is edited after I got my answer, but is there any way to do it the way I intended in the second delimiter, by using the "," as the delimiter?
Based upon the data given in your post, I think you can use this pattern ","|"
Following is the kind of code you can write,
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new FileInputStream("filename.txt"));
sc.useDelimiter(Pattern.compile("\",\"|\""));
while(sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();
}
If you just want a java written helpful csv parser. I wrote a pretty nice one recently:
public static Iterable<String[]> parseCSV(final InputStream stream) throws IOException {
return new Iterable<String[]>() {
#Override
public Iterator<String[]> iterator() {
return new Iterator<String[]>() {
static final int UNCALCULATED = 0;
static final int READY = 1;
static final int FINISHED = 2;
int state = UNCALCULATED;
ArrayList<String> value_list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String[] return_value;
public void end() {
end_part();
return_value = new String[value_list.size()];
value_list.toArray(return_value);
value_list.clear();
}
public void end_part() {
value_list.add(sb.toString());
sb.setLength(0);
}
public void append(int ch) {
sb.append((char) ch);
}
public void calculate() throws IOException {
boolean inquote = false;
while (true) {
int ch = stream.read();
switch (ch) {
default: //regular character.
append(ch);
break;
case -1: //read has reached the end.
if ((sb.length() == 0) && (value_list.isEmpty())) {
state = FINISHED;
} else {
end();
state = READY;
}
return;
case '\r':
case '\n': //end of line.
if (inquote) {
append(ch);
} else {
end();
state = READY;
return;
}
break;
case ',': //comma
if (inquote) {
append(ch);
} else {
end_part();
break;
}
break;
case '"': //quote.
inquote = !inquote;
break;
}
}
}
#Override
public boolean hasNext() {
if (state == UNCALCULATED) {
try {
calculate();
} catch (IOException ex) {
}
}
return state == READY;
}
#Override
public String[] next() {
if (state == UNCALCULATED) {
try {
calculate();
} catch (IOException ex) {
}
}
state = UNCALCULATED;
return return_value;
}
};
}
};
}
You would typically process this quite helpfully like:
for (String[] csv : parseCSV(stream)) {
//<deal with parsed csv data>
}
Generally it wraps a csv stream parser in an iterable so you can use the special java for loops. So you feed it a stream and it'll give you a for loop of arrays of strings, which is typically going to be the best way you'd want that data.
If you rather want understanding, you'll need to better phrase your question with additional information that makes it clear what you think you need and why, because most of your post doesn't make much sense.

How to print out a recursion method?

public class RecursionPracticeProgram {
KeyboardReader reader = new KeyboardReader();
public String backString(String s){
s = reader.readLine("String: ");
if(s.length()==0)
return s;
System.out.println(backString(s.substring(1)) + s.charAt(0));
return backString(s.substring(1)) + s.charAt(0);
}
public void run(){
backString("Fox");
}
I am doing some recursion work but am having trouble printing it out. I think I have the code correct for reversing a string but when I go to run the program it just builds and doesn't actually print anything out. How do I print it out properly?
You need to make sure to only read once and you call your method at all.
Just do it like this:
public class RecursionPracticeProgram {
public void run() {
String input = reader.readLine("String: ");
KeyboardReader reader = new KeyboardReader();
System.out.println(reader.backstring(input));
}
public String backString(String s){
if(s.length()==0)
return s;
System.out.println(backString(s.substring(1)) + s.charAt(0));
return backString(s.substring(1)) + s.charAt(0);
}
}

Java Error; array required, but java.lang.String found

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

Java returns impossible random numbers

Here is the code:
import java.lang.*;
import java.io.*;
class string
{
public static void main(String[] args)
{
try
{
boolean go = true;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer inp = new StringBuffer(br.readLine());
System.out.println(inp.reverse());
inp.reverse();
int leng = inp.length();
inp.setLength(leng+100);
int x = 0;
StringBuffer res = inp;
William bill = new William();
res=bill.will(x+1, leng, res);
while(x<leng-1 && go)
{
if(inp.charAt(x)==' ' && go)
{
res=bill.will(x+1, leng, res);
go = bill.bob();
}
x=x+1;
}
System.out.println(res);
}
catch (IOException uhoh)
{
System.out.println("You entered something wrong.");
System.exit(1);
}
}
}
class William
{
public boolean go;
public William()
{
this.go=true;
}
public StringBuffer will(int start, int len, StringBuffer input)
{
char cur = input.charAt(start-1);
input.delete(start-1, start-1);
int x = start;
boolean happy=true;
while(x<len && happy)
{
if(x==len-2)
{
this.go=false;
input.insert(cur, x+1);
x=x+2;
happy=false;
}
else if(input.charAt(x)==' ')
{
input.insert(cur, x);
x=x+1;
happy=false;
}
else
{
x=x+1;
}
}
return input;
}
public boolean bob()
{
return this.go;
}
}
It is supposed to return the reverse of the input (it does that without error) and the input in an altered form of pig latin. tI houlds ookl ikel hist ("It should look like this"). But instead, it returns the original StringBuffer with a bunch of random numbers on the end. Two notable patterns in the error include the increase in the numbers as the number of letters increases, as well as overflow errors when short strings are inputted.
You have the arguments to StringBuffer.insert() backwards. It's (offset, char)
try
input.insert(x+1, cur); instead of input.insert(cur, x+1);
(and same for input.insert(cur, x))

Categories