How to make this test pass? - java

How would i make a while loop to go through the characters of the Strings of text to find the first place there is a blank and returning the value of the position. I do i need a double condition in the while loop?
public class TestSentenceCounter
{
private static final String SENTENCE1 = "This is my sentence.";
private static final String SENTENCE2 = "These words make another sentence that is longer";
private SentenceCounter sc1;
private SentenceCounter sc2;
/**
* Create two instances we can play with
*/
#Before
public void setup()
{
sc1 = new SentenceCounter(SENTENCE1);
sc2 = new SentenceCounter(SENTENCE2);
}
/**
* Make sure the instance variable is correct
*/
#Test
public void testConstructor()
{
assertEquals(SENTENCE1, sc1.getSentence());
assertEquals(SENTENCE2, sc2.getSentence());
}
#Test
public void testFirstBlankPosition()
{
assertEquals(4, sc1.firstBlankPosition());
assertEquals(5, sc2.firstBlankPosition());
}
}
----------------------------------------------------
public class SentenceCounter
{
public String sentence;
public SentenceCounter(String sentence)
{
this.sentence = sentence;
}
public Object getSentence()
{
return sentence;
}
public Object firstBlankPosition()
{
return null;
}
}

Update your code accordingly ,
public int firstBlankPosition()
{
int returnVal = 0;
char ch ;
for(int i = 0 ; i < sentence.length() ; i++){
ch = sentence.charAt(i);
if(ch == ' '){
returnVal = i;
break;
}
}
return returnVal;
}

Related

How do you use methods from sub classes in the main class in Java?

I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.

How to return the value of a method where the method name is given by a string?

I need to return the value of a method and also I need to print the name of the method including the object by which it is called. For example:
public class FindMethod {
public void accessor(String m){
String amount = "getamount()" ;
String str="";
if(m.equals("Receive(int)"))
str+= "LS."+amount;
System.out.println(str);
}
public static void main(String[] args)
{
FindMethod fm = new FindMethod();
fm.accessor("Receive(int)");
}
}
Result: LS.getamount()
The above program is printing the method name as a string including the object where LS is the object and getamount() is the method of another class LoanApprovalSystem().
But I need to print the integer value that will be returned by the result LS.getamount(). But I have returned LS.getamount() as a string. I am not sure how to return the actual value of LS.getamount() from the string.
Can any one give me some idea that, how can I return the value of the method getamount() which is given by a string?? I mean can I use the string LS.getamount() as a reference to call the method getamount() from the class LoanApprovalSystem()??
The class LoanApprovalSystem() is given below:
public class LoanApprovalSystem {
private static int amount;
private static String risklevel ;
private static boolean approve;
private static boolean message;
private static String result ;
public LoanApprovalSystem(){
}
void initialize(){
amount=0;
risklevel=null;
approve=false;
message=false;
}
public void Receive(int req){
amount = req;
}
public void Asses(int req){
if (req > 1000 && req <= 5000)
{
risklevel = "low";
approve = true;
}
else if (req > 5000 && req <= 10000)
{
risklevel = "high";
}
else
risklevel = " ";
}
public void Approval(int req){
if ((req > 10000) || ((req <= 10000) & getrisklevel() =="high"))
{
approve = false;
}
else if (amount <= 5000 && getrisklevel() == "low")
{
approve = true;
}
}
public void Sendmessage(String risklevel){
if(risklevel == "low")
{
message=true;
//System.out.println(message);
//System.out.println("Loan approved");
}
else
message=false;
}
public void Reply(boolean message, boolean approve){
if(message == true || approve == true)
{
result = ("Loan Approved");
//System.out.println("Loan Approved");
}
else
{
result = ("Loan Rejected");
//System.out.println("Loan Rejected");
}
}
public int getamount(){
return (amount);
}
public String getrisklevel(){
return(risklevel);
}
public boolean getapprove(){
return (approve);
}
public boolean getmessage(){
return(message);
}
public String getresult(){
return (result);
}
public String toString(){
String str = "";
str += "(" +result+ ").";
return str;
}
public static void main(String[] args){
LoanApprovalSystem LS = new LoanApprovalSystem();
TestdataGeneration testdata = new TestdataGeneration();
LS.initialize();
//for(int data:testdata.Testdata())
{
LS.Receive(testdata.thirddata());
LS.Asses(LS.getamount());
LS.Approval(LS.getamount());
LS.Sendmessage(LS.getrisklevel());
LS.Reply(LS.getmessage(), LS.getapprove());
System.out.println("Final state: "+LS);
}
}
}
Use reflection:
http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
Class<?> c = Class.forName("className");
Method method = c.getDeclaredMethod ("methodName", parameterTypes)
Object o = method.invoke (objectToInvokeOn, paramList)
But usually you don't use reflection. Only if there is no other way to do.
Look for use and danger of reflection here https://softwareengineering.stackexchange.com/questions/123956/why-should-i-use-reflection

Java error - invalid method declaration; return type required

I'm trying to complete this java program, but every time I try to compile it I get this error. Can someone figure out why my program is doing this. It seems that no matter what I do I still happen to get an error on my program. I tried everything I know to see if it would work. Please someone help me.
import java.util.Scanner;
public class Period
{
private static String phrase;
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();
}
// this is where the error is occuring at.
public 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
{
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]);
}
}
}
The 'Sorter' method is missing a return type. It should be:
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0, newPhrase.indexOf("."));
}
The method is not called anywhere, so i am not sure if this is what you intended it to do.
add the void return type:
public void Sorter(String newPhrase) // HERE
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
There are a lot of errors in the above code - see below for some code that runs, though i can't be sure it does exactly what you want given the limited scope of the question.
I don't want to stray too far from the original question, but you should really consider using instance variables and encapsulating your data, rather than relying on static variables.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static int[] alphabet = new int [27];
public static void main(String [] args)
{
System.out.println("Enter a sentence with a period at the end.");
Scanner keyboard = new Scanner(System.in);
phrase = keyboard.nextLine().toLowerCase();
Period period = new Period();
period.entryPoint();
}
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
{
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]);
}
}
}

Reverse Linked List error- Java

I am trying to reverse a linked list in Java using stack I keep on receiving this error:
LinkStackApp.java:84: error: constructor LinkStack in class LinkStack cannot be applied to given types;
LinkStack stackrev = new LinkStack(stackSize);
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
1 error
I don't know where it finds int, I tried changing the Strings to char and vice versa but just keep on getting more errors any ideas? here is my full code:
import java.io.*;
import java.util.Scanner;
class Link
{
public char dData;
public Link next;
public Link(char dd)
{
dData = dd;
}
public void displayLink()
{
System.out.print(dData + " ");
}
}
class LinkList
{
private Link first; //ref to first item on the list
public LinkList() //no items on list yet
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insertFirst(char dd)
{
Link newLink = new Link(dd);
newLink.next = first;
first = newLink;
}
public char deleteFirst()
{
Link temp = first;
first = first.next;
return temp.dData;
}
public void displayList()
{
Link current = first;
while(current != null)
{
current.displayLink();
current = current.next;
}
System.out.println(" ");
}
}
class LinkStack
{
private LinkList theList;
public LinkStack()
{
theList = new LinkList();
}
public void push(char j)
{
theList.insertFirst(j);
}
public char pop()
{
return theList.deleteFirst();
}
public boolean isEmpty()
{
return (theList.isEmpty());
}
}
class Reverser{
private String input;
private String output;
public Reverser(String in){
input = in;
}
public String doRev(){
int stackSize = input.length();
LinkStack stackrev = new LinkStack(stackSize);
for (int j = 0; j <input.length(); j++){
char ch = input.charAt(j);
stackrev.push(ch);
}
output = "";
while(!stackrev.isEmpty()){
char ch = stackrev.pop();
output = output + ch;
}
return output;
}
}
class LinkStackApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String inputString, outputString;
while(true){
System.out.print("Enter A String: ");
inputString = input.nextLine();
if(inputString.equals(""))
break;
Reverser therev = new Reverser(inputString);
outputString = therev.doRev();
System.out.println("Reversed: "+outputString);
}
}
}
stackSize is an int. It's telling you to call the constructor with no params.
The correct constructor invocation is:
LinkStack stackrev = new LinkStack();

Reverse a string using a recursive void method

So I'm trying to write a method that reverses a given string but the catch is that it has to be a void method rather than a return method which is making this difficult. My code seems logical to me but it doesn't work so I'm hoping someone can help me figure out where I'm going wrong.
public class Reverser {
public String text, revText;
/**
* #param args
*/
public static void main(String[] args) {
Reverser greeting = new Reverser("Buildings");
greeting.reverse();
System.out.println(greeting.getText());
}
public Reverser(String _text){
text = _text;
}
public void reverse(){
int len = text.length();
if(len >= 1){
String last = text.substring(text.length() - 1, text.length());
revText += last;
text = text.substring(0, text.length() - 1);
Reverser loop = new Reverser(text);
loop.reverse();
}
}
public String getText(){
return revText;
}
}
Here's an idea:
public class Reverser {
private int idx;
private String text, revText;
public static void main(String[] args) {
Reverser greeting = new Reverser("Buildings");
greeting.reverse();
System.out.println(greeting.getText());
}
public void reverse() {
if (idx == text.length())
return;
revText = text.charAt(idx) + revText;
idx++;
reverse();
}
public Reverser(String _text) {
idx = 0;
text = _text;
revText = "";
}
public String getText() {
return revText;
}
}
The fundamental difference with respect to your answer, is that I'm using an index attribute to keep track of where exactly I am in the recursion. In that way, I don't have to modify the original text attribute.
A slighty different version to what Oscar Lopez responded is this
public class Sentence{
private String sntce, rvrse;
private int idx;
public Sentence(String sentence){
sntce = sentence;
rvrse = "";
}
/**
A method to reverse a string recursively.
#return void.
*/
void reverse(){
if (idx == sntce.length()){
sntce = rvrse;
return;
}
rvrse = sntce.charAt(idx) + rvrse;
idx++;
reverse();
}
/**
To test reverse gives the appropriate value.
#return the value of sntce.
*/
public String getText(){
return sntce;
}
}
Here's a version that uses as few instance variables as possible. Unfortunately you need at least one instance variable to hold the final result (result). Otherwise the state is passed into each recursive call.
(PS, is this homework?)
public class RecursiveVoidStringReverser {
public static void main(String[] args) {
final RecursiveVoidStringReverser reverser = new RecursiveVoidStringReverser();
reverser.reverse("Welcome to the jungle!");
System.out.println("reverser.result = " + reverser.result());
}
private String result;
public void reverse(String s) {
if ("".equals(s)) {
result = s;
} else {
reverse(s.toCharArray(), 0);
}
}
private void reverse(char[] chars, int index) {
if (index > chars.length / 2) {
result = new String(chars);
} else {
char t = chars[index];
chars[index] = chars[chars.length - index - 1];
chars[chars.length - index - 1] = t;
reverse(chars, index+1);
}
}
public String result() {
return result;
}
}
Given that a string is immutable, you cannot change it in situ. If the only requirement is that there be no return value, and it's okay simply to print out the final string (or to place it into a class variable), then this would work fine for any strings of at least one character:
public static void main(String args[])
{
reverse("", "original string");
}
public static void reverse(String reversed, String original)
{
if(original.length() <= 1)
{
System.out.println(original.charAt(0) + reversed);
// (or set it into a shared variable)
return;
}
reverse(original.charAt(0) + reversed, original.substring(1));
}
This solution is going for procedural simplicity, not memory efficiency. This produces quite an unpleasant memory footprint, essentially creating two in-memory strings for each character in the original. It is, however, very logically simple.
Of course, if you're just dumping out to console, then you can achieve the same thing using an algorithm that's pretty much the same as one with a return value:
public static void reverse(String original)
{
if(original.length() < 1) return;
System.out.print(original.charAt(original.length() - 1));
reverse(original.substring(0, original.length() - 1));
}

Categories

Resources