with statement to compare string - string

I'm trying to evaluate user input, but the while statement seems to go into an infinite loop without asking for input.
import javax.swing.JOptionPane;
public class StringMethodsTwo {
public static void main(String[] args)
{
String sFullName = " ";
String prompt = "Please enter your full name:";
while(sFullName.startsWith(" "));
{
sFullName = getInput(prompt);
if(sFullName.length() < 2)
{
prompt = "Please enter your full name, \"<first> <middle> <last>\":";
}
}
}
public static String getInput(String prompt)
{
return JOptionPane.showInputDialog(null, prompt);
}
}

You are doing the loop
while(sFullName.startsWith(" ")); // while(true);
{
Delete the ";"

Lose the semicolon at the end of your "while" line.

Related

how to fix a double substring call?

in my homework I need to extract the server name from the url
at the same time, I need to take into account that there may not be a slash after the server name
I'm not allowed to use a loop
At the same time, I am once again trying to redo a remark from my teacher:
"Now substring can be done twice (if it goes into if). You need to make sure that only one substring is made for any variant of the function execution"
how can this be fixed? I've tried everything
public class Url {
public static String getServerName(String url) {
int index1 = url.indexOf("://") + 3;
String serverName = url.substring(index1);
int index2 = serverName.indexOf("/");
if (index2 >= 0) {
return url.substring(index1, index1 + index2);
}
return serverName;
}
public static void main(String[] args) {
String url = "https://SomeServerName";
System.out.println(getServerName(url));
}
}

Weired problem after reading input from keyboard

edit: The ArrayList wasn't needed to reproduce the "error". Sorry for this delay, but know it should be much clearer.
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
package com.example.mypackage;
import java.util.ArrayList;
import java.util.Scanner;
class Contact {
public String name;
public String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public void print(){
System.out.println(name+number);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null) {
return false;
} else if (obj instanceof Contact) {
Contact contact = (Contact) obj;
if ((contact.name == this.name && contact.number == this.number)) {
return true;
}
}
return false;
}
}
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Contact c1 = new Contact("ben", "1");
c1.print();
Contact c2 = new Contact("ben", "1");
c2.print();
System.out.println("name : ");
String name=scanner.nextLine();
System.out.println("number");
String number=scanner.nextLine();
Contact c3=new Contact(name, number);
c3.print();
System.out.println("c1.equals(c2) = "+c1.equals(c2));
System.out.println("c3 instanceof Contact = "+(c3 instanceof Contact));
System.out.println("c2.name.equals(c3.name) = "+c2.name.equals(c3.name));
System.out.println("c2.number.equals(c3.number) = "+c2.number.equals(c3.number));
System.out.println("c2.number.equals(c3.number) = "+c3.equals(c2));
}
}
Output is:
ben1
ben1
name :
ben
number
1
ben1
c1.equals(c2) = true
c3 instanceof Contact = true
c2.name.equals(c3.name) = true
c2.number.equals(c3.number) = true
c2.number.equals(c3.number) = false
Process finished with exit code 0
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Ah finally I got it. The error is in the equals method.
I must use "equals()" instead of "==" there. For some reason this comparison does work with c1 and c2 but not with c3.
-1 is returned if it wasn't found in the list.
Did you forget to myList.add() it?
The only add I see is when you added c1.
You need to myList.add(c3) after you get the input, or it won't be in the list to find an index of.

Error: NoSuchElementException

This program accesses a text file with text elements separated by commas. The elements register in the variables I created. Except for the last one. The error then occurs. The program works fine with the default whitespace delimitor for the scanner class (the text file is adjusted accodingly) but fails when I use a comma as the delimitor. Could someone please supply some insight.
Text Data:
smith,john,10
stiles,pat,12
mason,emrick,12
Code:
public void openFile(String f)
{
try{
x = new Scanner(new File(f));
x.useDelimiter(",");
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNext())
{
String lName = x.next().trim();
**String fName = x.next().trim();**
String grade = x.next().trim();
if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
The problem relies on the fact that you called x.useDelimiter(","); on your Scanner in function openFile().
Since your text data is:
smith,john,10
stiles,pat,12
mason,emrick,12
the Scanner sees it as:
"smith,john,10\nstiles,pat,12\nmason,emrick,12"
So what happens when you execute your code is:
1: x.hasNext() ? Yes
x.next().trim() => "smith"
x.next().trim() => "john"
x.next().trim() => "10\nstiles"
2: x.hasNext() ? Yes
x.next().trim() => "pat"
x.next().trim() => "12\nmason"
x.next().trim() => "emrick"
3: x.hasNext() ? Yes
x.next().trim() => "12"
x.next().trim() => Error!
To fix this you can either edit the file and change all the \n with ,, or use a first Scanner to get all the lines, and another one to get the tokens, as shown here:
public void openFile(String f)
{
try{
x = new Scanner(new File(f)); // Leave default delimiter
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNextLine()) // For each line in your file
{
Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
String lName = x.next().trim();
String fName = x.next().trim();
String grade = x.next().trim();
if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}

If Else: String Equality (Java)

Lab Description : Compare two strings to see if each of the two strings contains the same letters in the
same order.
This is what I have so far far:
import static java.lang.System.*;
public class StringEquality
{
private String wordOne, wordTwo;
public StringEquality()
{
}
public StringEquality(String one, String two)
{
setWords (wordOne, wordTwo);
}
public void setWords(String one, String two)
{
wordOne = one;
wordTwo = two;
}
public boolean checkEquality()
{
if (wordOne == wordTwo)
return true;
else
return false;
}
public String toString()
{
String output = "";
if (checkEquality())
output += wordOne + " does not have the same letters as " + wordTwo;
else
output += wordOne + " does have the same letters as " + wordTwo;
return output;
}
}
My runner looks like this:
import static java.lang.System.*;
public class StringEqualityRunner
{
public static void main(String args[])
{
StringEquality test = new StringEquality();
test.setWords(hello, goodbye);
out.println(test);
}
}
Everything is compiling except for the runner. It keeps saying that hello and goodbye aren't variables. How can I fix this so that the program does not read hello and goodbye as variables, but as Strings?
You need to quote strings otherwise they are treated as variables.
"hello"
"goodbye"
so this would work better.
test.setWords("hello", "goodbye");
Problem with your code is with checkEquality(), you are comparing the string's position in memory when you use == use .equals() to check the string
public boolean checkEquality()
{
if (wordOne == wordTwo) //use wordOne.equals(wordTwo) here
return true;
else
return false;
}
Enclose them in double-quotes.

Getting highest available string in java

I want to get the highest available string value in java how can i achieve this.
Example: hello jameswangfron
I want to get the highest string "jameswangfron"
String Text = request.getParameter("hello jameswangfron");
Please code example.
public class HelloWorld{
public static void main(String []args){
String text = "hello jameswangfron";
String[] textArray = text.split(" ");
String biggestString = "";
for(int i=0; i<textArray.length; i++){
if(i==0) {
textArray[i].length();
biggestString = textArray[i];
} else {
if(textArray[i].length()>textArray[i-1].length()){
biggestString = textArray[i];
}
}
}
System.out.println("Biggest String : "+biggestString);
}
}
And it shows the output as
Biggest String : jameswangfron
Maybe this will be easyer to understand
public class HelloWorld {
public static void main(String[] args) {
System.out.println(StringManipulator.getMaxLengthString("hello jameswangfron", " "));
}
}
class StringManipulator{
public static String getMaxLengthString(String data, String separator){
String[] stringArray = data.split(separator);
String toReturn = "";
int maxLengthSoFar = 0;
for (String string : stringArray) {
if(string.length()>maxLengthSoFar){
maxLengthSoFar = string.length();
toReturn = string;
}
}
return toReturn;
}
}
But there is a catch. If you pay attention to split method from class String, you will find out that the spliter is actually a regex. For your code, i see that you want to separate the words (which means blank space). if you want an entire text to search, you have to pass a regex.
Here's a tip. If you want your words to be separated by " ", ".", "," (you get the ideea) then you should replace the " " from getMaxLengthString method with the following
"[^a-zA-Z0-9]"
If you want digits to split up words, simply put
"[^a-zA-Z]"
This tells us that we use the separators as anything that is NOT a lower case letter or upper case letter. (the ^ character means you don't want the characters you listed in your brackets [])
Here is another way of doing this
"[^\\w]"
\w it actually means word characters. so if you negate this (with ^) you should be fine

Resources