Java Beginning Scanner - java

I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.

You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)

Related

basic Java coding question about reversing order of words for JAVA

I am looking for a way to reverse the word in java.
This is my code and it occurs errors.
Can somebody explain why?
import java.util.Scanner;
public class Robot {
public static void reverse(String text) {
int leng = text.length();
int i = 0;
while (leng-i>=0){System.out.print(text.charAt(leng-i));
i++;
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type in your text: ");
String text = reader.nextLine();
System.out.print("In reverse order: ");
reverse(text);
}
}
I expected it to reverse the order of the word but it does not.
It should be
int i = 1;
Otherwise, you will be getting a StringIndexOutOfBoundsException since text.length() is never a valid index.
To make it a bit shorter (and cooler), you might want to write
System.out.print(text.charAt(leng - i++));
Though, we usually do
System.out.print(new StringBuilder(text).reverse());
Your problem is here:
int leng = text.length();
arrays in java are 0-indexed, which means that the last character in the string is at index (text.length()-1), instead of text.length()
So, you can set leng to text.length()-1, or you can set i to 1

Why is my radix sorting algorithm returning a partially sorted list?

First off I want to point out that this assignment is homework /but/ I am not looking for a direct answer, but rather at a hint or some insight as to why my implementation is not working.
Here is the given: We are provided with a list of words of 7 characters long each and are asked to sort them using the Radix Sorting Algorithm while using queues.
EDIT 1: Updated Code
Here is my code:
import java.util.*;
import java.io.File;
public class RadixSort {
public void radixSort() {
ArrayList<LinkedQueue> arrayOfBins = new ArrayList<LinkedQueue>();
LinkedQueue<String> masterQueue = new LinkedQueue<String>();
LinkedQueue<String> studentQueue = new LinkedQueue<String>();
//Creating the bins
for (int i = 0; i < 26; i++) {
arrayOfBins.add(new LinkedQueue<String>());
}
// Getting the file name and reading the lines from it
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with its extension: ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
masterQueue.enqueue(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int p = 6; p >= 0; p--) {
for (LinkedQueue queue : arrayOfBins) {
queue.clear();
}
while (masterQueue.isEmpty() == false) {
String s = (String) masterQueue.dequeue();
char c = s.charAt(p);
arrayOfBins.get(c-'a').enqueue(s);
}
for (LinkedQueue queue : arrayOfBins) {
studentQueue.append(queue);
}
}
masterQueue = studentQueue;
System.out.println(masterQueue.size());
System.out.println(masterQueue.dequeue());
}
public static void main(String [] args) {
RadixSort sort = new RadixSort();
sort.radixSort();
}
}
I can see so many problems, I'm not sure how you get an answer at all.
Why do you have two nested outermost loops from 0 to 6?
Why don't you ever clear studentQueue?
The j loop doesn't execute as many times as you think it does.
Aside from definite bugs, the program doesn't output anything -- are you just looking at the result in the debugger? Also are you actually allowed to assume that the words will contain no characters besides lowercase letters?

Trouble matching states to capitals

I created two arrays and assigned states to one array and capitals to the other array that I got from a text file. The text file is formatted like this:
Colorado,Denver,
Wisconsin,Madison,
..........etc
My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
int a = currentLine.indexOf(",");
String states1 = currentLine.substring(0, a);
states[i] = states1;
int b = currentLine.lastIndexOf(",");
String capitals1 = currentLine.substring(a+1, b);
capitals[i] = capitals1;
}//end for loop
}
}
The point of my program is to ask "What is the capital of (blank)?"
Then I need to tell the person if they are correct or not. The problem I'm having is that I don't know how to check if, for example, Madison is the capital of Wisconsin. Any help would be appreciated.
public static void main(String[] args) {
Scanner userInput = null;
Scanner scanner = null;
try {
userInput = new Scanner(System.in);
scanner = new Scanner(new File("capitals.txt"));
while (scanner.hasNext()) {
String[] stateAndCapital = scanner.next().split(",");
System.out.println(String.format("What is the capital of %s?",
stateAndCapital[0]));
System.out.println(userInput.next().equals(stateAndCapital[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
userInput.close();
}
}
output:
What is the capital of Colorado?
dunno
false
What is the capital of Wisconsin?
Madison
true
Try using this:
public boolean isCapitalOfState(String capital, String state) {
for (int i = 0; i < state.length; i++) {
if (state[i].equals(state) && capitals[i].equals(capital)) {
return true;
}
}
return false;
}
It loops through the array of states and once it has found the match, it will check if the capital matches, if so return true. If it has not found anything it will by default return false.
Note though that there are a lot of easier ways to achieve your behaviour. Generally, Lists are superior to Arrays.
EDIT: I see your question asks for a bit more, we here cannot give you a full program to do it. However do keep in mind that when you've already obtained an index in state, that you can check the result way easier than this.
These are setup like parallel arrays correct? Meaning for example states[0] = colorado, and capitals[0] = denver, it looks this way but if it is indeed setup like this use the index of the state as the index for the capital and compare the input against that.
For example,
System.out.println("What is the capital of " + states[i]);
capital = input.nextLine();
if(capital.equals(capitals[i]){
return true;
}
else{
return false;
}

How do I make an array from a file containing numbers in Java?

Im fairly new to java, and I have a project to make a program that reads a file containing a list of numbers and calculates them. I want to make an array after reading the file, but can't seem to use the array 'scores[]' that I created in my makeArray method. Could someone please show me how to fix this error? I believe it is something to do with scope, I just can't figure it out. Also, I know lists can work instead of arrays but I can't use the for this project. Thanks!
P.S. sorry If my codes ugly
import java.io.*;
import java.util.*;
class GradeFiles {
public static void main(String[] args)
throws FileNotFoundException {
Scanner console = new Scanner(System.in);
Scanner input = promptUser(console);
for(int i = 0; i<= scores.length-1; i++) {
double[] printArray = scores[i];
System.out.print(printArray);
}
}
public static Scanner promptUser(Scanner console)
throws FileNotFoundException {
Scanner isThere = null;
while(isThere == null) {
System.out.print("Enter name of file: ");
String fileName = console.next();
try {
isThere = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.print("File Not Found. ");
}
}
System.out.print("");
return isThere;
}
public static double[] makeArray(Scanner input) {
int length = 0;
while(input.hasNext()) {
double a = input.nextDouble();
length++;
}
double[] scores = new double[length-1];
while(input.hasNext()) {
for(int i = 0; i <= length - 1; i++) {
double num = input.nextDouble();
scores[i] = num;
}
}
return scores;
}
}
you are going to the end of the file in an attempt to find the number of double values you need to store so that you can decide the length of the array. So when you are again using
input.hasNext(); it returns null because you are already at the end of the file.
You can use an arrayList to read the numbers if you are unsure about how many you have to read. If you want you can cast it back to array
public static double[] makeArray(Scanner input) {
int length = 0;
ArrayList<Double> list = new ArrayList<Double>();
while(input.hasNext()) {
list.add(input.nextDouble());
}
double[] scores = new double[list.size()];
int i = 0;
for (double e : list)
scores[i++] = e;
return scores;
}
Look at the makeArray method you've written. in the first loop you advance the scanner pointer to the end of the file.
surly if you try to read additional data there will be no more (next()).
the most simple solution is that you reconstruct your scanner passing it the same file after completing the first loop.
makeArray will always return an empty array. After you scan through input.hasNext() you have consumed all of your input. The second while loop will exit immediately because there is no more input.

Why am I getting "java.lang.NumberFormatException" when trying to convert this string into an integer?

I have been creating a Java program to encode a message received from the user. Just for some background into how it does this: It is supposed to get the input, split it into characters, then get a set of random numbers from Random.org (true random number generator) equal to the length of the message and then shift the characters of the input by their corresponding shift, or random number, then output the coded message and the shifts. So far I have gotten input, converted it into a string array, checked the quota (Random.org has a quota) and gotten the random numbers. I am getting this error when trying to output the converted shifts (from Strings gotten at the website to ints), I think it is because of a CRLF on the last number (I tried using a regex to fix this, but it didn't work). Here is my code:
public class Encryption_System {
static String originalMessege;
public static void main(String[] args) throws Exception {
System.out.println("Welcome to the encryption system!");
System.out.println("Type your messege below:");
System.out.println("\nHere is your original messege: " + scan() + "\n");
Encrypt code = new Encrypt();
code.Messege(originalMessege);
code.encryptMessege();
}
private static String scan() {
Scanner scan = new Scanner(System.in);
originalMessege = scan.nextLine();
return originalMessege;
}
}
Then there is a second class, where my problem originates. My error comes from the last method (my attempted regex fix is commented out):
public class Encrypt {
private String messege;
private String[] characters;
private URL quotaURL;
private URLConnection conect;
private InputStream quotaInput;
private BufferedReader quotaReader;
private int quota;
private boolean go;
private URL shiftsURL;
private URLConnection conectShifts;
private InputStream shiftsInput;
private BufferedReader shiftsReader;
private int count;
private char[] shifts;
private int[] shiftsInt;
private String shiftsString;
private String[] shiftsStrings;
public void Messege(String x) {
messege = x;
}
private String[] getCharacters() {
characters = messege.split("(?!^)");
return characters;
}
private boolean checkQuota() throws Exception {
quotaURL = new URL("http://www.random.org/quota/?format=plain");
conect = quotaURL.openConnection();
quotaInput = conect.getInputStream();
quotaReader = new BufferedReader(new InputStreamReader(quotaInput));
int quota = Integer.parseInt(quotaReader.readLine());
if (quota >= getCharacters().length)
go = true;
else
go = false;
return go;
}
private char[] Shifts(String[] x1) throws Exception {
String[] messegeArray = x1;
count = 0;
for (int k = 0; k < x1.length; k++) {
if (x1[k].equals(" ")) {
continue;
} else {
count++;
}
}
shifts = new char[count * 3];
if (checkQuota() == true) {
shiftsURL = new URL("http://www.random.org/integers/?num=" + count
+ "&min=1&max=27&col=" + count
+ "&base=10&format=plain&rnd=new");
conectShifts = shiftsURL.openConnection();
shiftsInput = conectShifts.getInputStream();
shiftsReader = new BufferedReader(
new InputStreamReader(shiftsInput));
shiftsReader.read(shifts, 0, count * 3);
}
return shifts;
}
public void encryptMessege() throws Exception {
char[] currentShifts = Shifts(getCharacters());
shiftsString = new String(currentShifts);
// shiftsString.replace("[\t\r\n]", "");
shiftsStrings = shiftsString.split("[( )]");
shiftsInt = new int[shiftsStrings.length];
System.out.println("These are your shifts");
for (int v = 0; v < shiftsInt.length; v++) {
shiftsInt[v] = Integer.parseInt(shiftsStrings[v]);
System.out.println(shiftsInt[v] + " ");
}
}
}
and here is my output:
Welcome to the encryption system!
Type your messege below:
Hello
Here is your original messege: Hello
These are your shifts
3
19
12
3
Exception in thread "main" java.lang.NumberFormatException: For input string: "12
Process completed.
I am just a Java beginner (first year high school comp sci), so thanks for any help!
Your code is failing for me because:
shiftsStrings = shiftsString.split("[( )]");
is not properly splitting the values.
EDIT:
Try This:
public void encryptMessege() throws Exception {
List<Integer> shifts = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(new String(Shifts(getCharacters())));
while(st.hasMoreTokens())
{
String token =st.nextToken();
try{
shifts.add(Integer.parseInt(token));
}catch(NumberFormatException e)
{
System.out.println("did not parse: " + token);
}
}
System.out.println("These are your shifts: " + shifts.toString());
}
Note there are a lot of things you should work on in your code.
1) Encapsulating functionality within methods. It gets confusing when you keep all your variables as class level attributes. If you pass them between methods using parameters, you gain easier to read code, and it's easier to test bits of your code.
2) You should start method names with lower case letters. This is common Java coding practice.
If you think it is due to non-number characters in the last number, then before putting it in parseInt use Replace on it with the characters that are non-number (you can use \r, \n and so on too).
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace(char, char)
Trim is another useful method, it removes all leading and trailing whitespace.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim()
The problem seems to be originating from here:
shiftsInt[v]= Integer.parseInt(shiftsStrings[v]);
And this fails when in the for loop value of v reaches 4. Remove the expression from the for loop and see if every string in shiftsStrings can actually be parsed to int. Try executing this:
for(int v = 0; v < shiftsStrings.length; v++ ) {
System.out.println(shiftsStrings[v]);
}
If there is something unexpected in the output, the next step would be to find out (and possibly remove) how that value found its place in the array.

Categories