import java.io.File;
import java.util.Scanner;
public class scoresedit {
public static void main(String[] args) throws Exception{
System.out.println("Reads in a file at the beginning of a loop, displays these top 3 scores by name and their respective score." +
"\nEnter a new name and score following a prompt. " +
"\nIf the new name and score exceeds one of the top three scores," +
"\nplaces the new name in the top three, moving all lower scores down, dropping the lowest score." +
"\nSaves the results in the file top3Scores.txt." +
"\nStops the loop when exit is entered for a name.");
File r = new File ("top3Scores.txt");
System.out.println(r);
String str = readSource (r);
System.out.println(str);
String[] strArray = new String[] {str};
Scanner in = new Scanner(System.in);
System.out.print("Enter a new name and score or 'exit' to quit:");
String nameAndScore = in.nextLine();
String[] nameAndScoreArray = new String[] {nameAndScore};
String nameAndScoreArray1[] = nameAndScore.split(" ");
while (nameAndScore != "exit") {
if (nameAndScoreArray[1] > strArray[1]) }
}
private static String readSource(File r) throws Exception{
Scanner in;
in = new Scanner (r);
String str = "";
while (in.hasNext())
str += in.nextLine() +"\n";
in.close();
return str;
}
}
I keep getting the error "The operator > is undefined for the argument type(s) java.lang.String, java.lang.String" when I try to compare the two arrays and I don't know how to fix it. The code isn't finished; obviously I'm adding more under the if statement but I want to resolve this first.
You are trying to compare nameAndScoreArray[1] and strArray[1] which are strings, I assume they contain the scores of two teams and the one with the highest score wins, so you want to use Integer.parseInt(String string) in order to see which one has the highest score:
if (Integer.parseInt(nameAndScoreArray[1]) > Integer.parseInt(strArray[1]))
You can not compare String with the operators <, >, instead you need to use compareTo.
Related
Very new to programming, just starting a Java class.
Here is what the assignment says
1.) Input, via a question in the console, the report owner’s first name as a string and build the last name via input, one character at a time.
a. Check, conditionally, to make sure the first name and last name don’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The names can not contain any white space either or special characters.
I already did the first part, and here is my code:
package inclassassignment;
import java.util.Scanner;
public class inclassassignment {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println ("Enter your first name");
String temp;
Scanner your_name = new Scanner (System.in);
temp = your_name.nextLine();
System.out.println(temp);
int n = 0;
System.out.println ("Enter your last name");
String temp1;
temp1 = "";
while (n < 6) {
System.out.println("Please print the next letter of your last name");
String nextletter1;
Scanner lastname = new Scanner (System.in);
nextletter1 = lastname.nextLine();
char nextletter = nextletter1.charAt(0);
temp1 = temp1 + nextletter;
n++;
}
System.out.println(temp1);
{
}
}
}
// I now need to do the part that says to check each ASCII value and make sure none of the letters contain a number. I'm pretty sure this requires an "if else" statement but I've never written one to success.
edit: I should point out I am not allowed to have any static variables or methods in any class except for the class with the main method.
According to your task, you can do it in this way:
int n = 0;
System.out.println("Enter your last name");
String lastName = "";
while (n < 6) {
System.out.print("Please print the next letter of your last name: ");
String tmp = your_name.nextLine();
char c = tmp.charAt(0);
if (Character.isAlphabetic(c)) {
lastName += c;
n++;
} else {
System.out.println("You can use only letters! Try again!");
}
}
System.out.println(lastName);
You can use regular expressions
Scanner sc=new Scanner(System.in);
String s= sc.nextLine(); //read the string
String regex1 = "\\d+" // the regular expression for numbers
if(s.matches(regex1)) // check if the string contains numbers
System.out.println("contains numbers");
I would start with a utility method to normalize names based on your required rules, Character.isUpperCase(char) or Character.isLowerCase(char) and a for-each loop over String.toCharArray() like,
static String normalizeName(String name) {
StringBuilder sb = new StringBuilder();
for (char ch : name.toCharArray()) {
if (Character.isUpperCase(ch) || Character.isLowerCase(ch)) {
sb.append(ch);
}
}
return sb.toString();
}
Then you can call it (and I would use it for both firstName and lastName, for consistency). Like,
public static void main(String[] args) {
System.out.println("Enter your first name");
Scanner scan = new Scanner(System.in);
String firstName = normalizeName(scan.nextLine());
System.out.println("Enter your last name");
String lastName = normalizeName(scan.nextLine());
System.out.printf("Hello %s %s%n", firstName, lastName);
}
Pretty sure this is posted elsewhere
str.matches(".*\\d+.*")// To check if string contains numbers
Try this function:
public String removeNum(String in){
String[] input= in.split("");
String num= "0123456789";
String[] numbers= num.split("");
List<String> numbersToDelete = Arrays.asList(numbers);
for(int i=0;i<input.length;i++){
if(numbersToDelete.contains(input[i])){
input[i]="";
}
}
//Converting from Array back to String
String out = "";
for(int j=0;j<input.length;j++){
out=out+input[j];
}
return out;
}
My example text:
This-File-Contains-184-Characters.
The-Most-Frequent-Letter-Is-"E".
The-File-Includes-2-Upper-Case-Occurences
And-22-Lower-Case-Occurences-Of-"E".
The-Total-Number-Of-Its-Occurences-Is-24.
The example letter I'm using is "e".
My code:
import java.io.*;
import java.util.Scanner;
public class Homework4a
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of the input file: ");
String fileName = keyboard.nextLine();
System.out.println("Enter letter: ");
char letter = keyboard.nextLine().charAt(0);
File file = new File(fileName);
Scanner scan = new Scanner(new FileReader(file));
try
{
char lowerCaseLetter = (new Character(letter)).toString().toLowerCase().charAt(0);
char upperCaseLetter = (new Character(letter)).toString().toUpperCase().charAt(0);
int lowerCounter=0;
int upperCounter = 0;
while(scan.hasNextLine())
{
String input = scan.nextLine();
for(int i=0; i<input.length(); i++)
{
if(input.charAt(i)== lowerCaseLetter)
{
lowerCounter++;
}
else if(input.charAt(i)== upperCaseLetter)
{
upperCounter++;
}
}
}
int totalLowerCounter = lowerCounter;
int totalUpperCounter = upperCounter;
int totalCounterSum = totalLowerCounter + totalUpperCounter;
System.out.println("The lower-case letter " + lowerCaseLetter + " occurs " + totalLowerCounter + " times");
System.out.println("The upper-case letter " + upperCaseLetter + " occurs " + totalUpperCounter + " times");
System.out.println("The total number of occurrences (\"" + lowerCaseLetter + "\" and \"" + upperCaseLetter +
"\") is " + (totalCounterSum));
}
finally
{
scan.close();
}
}
}
I'll give you some pointers. My best advice is to use divide & conquer:
Get the file name from user input (you already know about Scanner)
Read the text file (check out BufferedReader and FileReader)
Remember that a char is basically just an int, look up an ASCII table
You can therefore use an array (int[]) where the indices are the ASCII values, the values are the number of occurence
Go over the contents of the file, char by char, and add to the array accordingly
Basically, divide & conquer is all about splitting a task into its smallest problems, then tackle them individually. By breaking an assignment down in this way, even quite complex problems will come down to small problems that are easy to solve.
What's also nice is that once you've broke it down like that, you can go ahead and write a method for each of these sub-tasks. This way, you get a nicely organized code "for free".
I figured out the problem, I needed to have the println outside of the loop. This code can help you read a text file and find a specific character by changing the variable in the "if else" statement to the specific character you need to find in the text file. It then calculates how many lowercase and uppercase letter and the total of them both.
Here is the code that u can formulate to find a letter count from a text file.i have pushed an harcoded letter 'a' u can change it to dynamic also.
import java.io.*;
import java.util.Scanner;
public class CountTheNumberOfAs {
public static void main(String[] args)throws IOException
{
String fileName = "JavaIntro.txt";
String line = "";
Scanner scanner = new Scanner(new FileReader(fileName));
try {
while ( scanner.hasNextLine() ){
line = scanner.nextLine();
int counter = 0;
for( int i=0; i<line.length(); i++ ) {
if( line.charAt(i) == 'a' ) {
counter++;
}
}
System.out.println(counter);
}
}
finally {
scanner.close();
}}}
So when I run my program's main method it prints:
Enter number of test cases:
1
Enter string 1
Enter string 2
rat apple cat ear cat apple rat
For some reason it prints Enter string 1 and Enter string 2 before I even put in anything for String one. Can anyone shed any light as to why this is happening. Is there something wrong with the way I have the BufferReader setup?
Code:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int testcases = in.read();
System.out.println("Enter string 1");
String[] str1 = in.readLine().split(" ");
System.out.println("\nEnter string 2");
String[] str2 = in.readLine().split(" ");
for(int i = 0; i < testcases; i++)
{
String result = lcss(str1, str2);
System.out.println("\nLCSS: "+ result);
System.out.println("\nLCSS Length = "+ result.length());
}
}
Please use the following.
int testcases = Integer.valueOf(in.readLine());
Read more on BufferedReader.read()
int testcases = in.read(); doesn't read the line break (when you press Enter).
The readLine() in the line String[] str1 = in.readLine().split(" "); will now begin to read directly after the number you entered and search for the next line break. The line break from you entering the number is now found and the function directly returns without waiting for your input.
So much for the explanation on what causes your program to behave the way it does.
Now you do have another error, as BufferedReader.read() doesn't do what you think it does. Check the documentation
So when you enter a 1 your testcases varaible will contain the UTF-16 value of the character '1' which is 31.
As other answers already pointed out you should either use Integer.valueOf(in.readLine()); to get the value for testcases or use Scanner
EDIT:
Get the number of test cases as integer
Create a 2 dimensional array to store test cases. First dimension holds each test case & second dimension holds String[] of word list in each test case.
Iterate through "for loop" until you get each test case string array for total number of test cases,
Sample code:
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int testcases = in.nextInt();
System.out.println("test cases:"+testcases);
String[][] strs = new String[testcases][];
for ( int i =0; i< testcases ; i++ ){
System.out.println("Enter string:"+i);
in = new Scanner(System.in);
if (in.hasNext()) {
String s = in.nextLine();
System.out.println(s);
strs[i] = s.split(" ");
System.out.println("Length:"+strs[i].length);
}
System.out.println();
}
// Add your logic
}
My school project requires me to modify my last assignment (code below) to pull a random phrase from a list of at least 10 for the user to guess. I drawing a blank on this. Any help would be appreciated. I understand I have to add a class that would import the text file or list, then I would need to modify a loop in order for it to randomly select?
import java.util.Scanner; // Allows the user to read different value types
public class SecretPhrase {
String phrase; //
Scanner scan = new Scanner(System.in);
SecretPhrase(String phrase){
this.phrase = phrase.toLowerCase();
}
public static void main(String args[]){
SecretPhrase start = new SecretPhrase("Java is Great"); // The phrase the user will have identify
start.go(); // Starts Program
}
void go(){
String guess;
String word="";
String[] words = new String[phrase.length()]; // array to store all charachters
ArrayList<String> lettersGuessed = new ArrayList();
for(int i=0;i<phrase.length();i++){
if(phrase.charAt(i)== ' '){words[i] = " ";}
else{words[i] = "*";} // Array that uses * to hide actual letters
}
int Gcount =0; // Records the count
while(!word.equals(phrase)){ // continues the loop
word = "";
int Lcount = 0;
System.out.print("Guess a letter> ");
guess = scan.next();
for(int i=0;i<phrase.length();i++){ // Accounts for any attempts by user to use more than one charachter at a time.
if((guess.charAt(0)+"").equals(phrase.charAt(i)+"")&&(lettersGuessed.indexOf(guess.charAt(0)+"")==-1)){
words[i] = ( guess.charAt(0))+ "";
Lcount++;
}
}
lettersGuessed.add(guess.charAt(0)+""); // Reveals the letter in phrase
System.out.println("You found " + Lcount +" letters"); // Prints out the total number of times the charachter was in the phrase
for(int i=0;i<words.length;i++){
word=word+words[i];
}
System.out.println(word);
Gcount ++;
}
System.out.println("Good Job! It took you " + Gcount + " guesses!" ); // Prints out result with total count
}
}
In the existing code, you are creating a SecretPhrase object with the phrase to guess:
public static void main(String args[]){
SecretPhrase start = new SecretPhrase("Java is Great");
start.go(); // Starts Program
}
You should replace it with a List (either ArrayList or LinkedList would be fine) and populate it with your data (given by either file, user input or hard-coded):
ArrayList<SecretPhrase> phrases = new ArrayList<SecretPhrase>();
//reading from file:
File file = new File("myPhrases.txt");
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String phrase = null;
while ((phrase = br.readLine()) != null) {
phrases.add(new SecretPhrase(phrase));
}
Now either use Random on phrases.size() and execute go on it, or if you're looking for it to be a series of phrases, you can create a permutation and loop over them. I'm not sure what your requirements here are.
This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.