I want to the longest name for 5 given names. I think I should use compareTo() method or length()?
Output must be like this :
enter 5 names :
Joey
Mark
Catherine
Zachery
Foster
Longest name is Catherine.
What method should I use and how? This is my code so far:
Scanner x = new Scanner(System.in);
String name = ""
System.out.print("Enter 5 names");
name = x.nextLine();
name2 = x.nextLine();
name3 = x.nextLine();
name4 = x.nextLine();
name5 = x.nextLine();
if(name.compareTo(name2)>0) //is this method right?
.compareTo tells you which string comes first in lexicographic order (<0 if s1 < s2, 0 if s1==s2, >0 if s1>s2)
String s1 = "abc";
String s2 = "def";
s1.compareTo(s2) < 0;
.length() returns the length of a string
s1.length()==3;
In your case, you need to compare based on length, so you need the latter. If it's only 5 names, you can take the first and assume it's the longest, and then read the others one by one by keeping the "longest so far" saved and comparing them as they come. After all, you only care about the longest.
If you wanted them to be sorted by length, while still keeping them all, you'd need to store them in some sort of collection (list, array), then sort it based on length.
The problem is easy enough, so I won't provide directly the code, try to grok it yourself, you can do it :)
import java.util.Scanner;
public class LenghtyName {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
/*
Instead of declaring 5 different String variable
just use String array with size = 5
*/
String[] names = new String[5];
System.out.print("Enter 5 names :");
names[0] = x.nextLine();
names[1] = x.nextLine();
names[2] = x.nextLine();
names[4] = x.nextLine();
names[5] = x.nextLine();
//Assume lenthyName as empty String
String lengthyName = "";
/*
Iterate over String array using for-each loop
*/
for (String name : names) {
/*
-Check null to avoid NullPointerException
-Trim the left and right blank space in name by #trim()
-Compare current name length with lengthyName if greater
replace the lengthyName by current name.
*/
if (name != null && name.trim().length() > lengthyName.length()) {
lengthyName = name;
}
}
/*
Print length name
*/
System.out.println("Longest name is " + lengthyName);
}
}
What about this?
Scanner in = new Scanner(System.in);
// no need to have 5 all over the code.
// Define it once to avoid "magic nubmers"
int namesCount = 5;
// fun fact: shortest name is always "". We don't have to use null
String longestName = "";
System.out.print("Enter " + nameCount + " names:");
for (int i=0; i< nameCount; i++){
// store new name from user
String candidate = in.readLine();
// is this one longer than the current longest?
if (longestName.length() < candidate.length()){
// found a longer name
longestName = candidate;
}
}
System.out.println("Longest name is " + longestName);
This gives up storing the names, as it seems you only use the longest one anyway. It also generalizes the number of names to iterate, and most importantly the variable names are meaningful names.
Here's a solution that should work:
public class LongestWord {
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static void main(String[] args) {
String[] toppings = {"Cheeddddddddddse", "Pepperoni", "Black Olivesddd"};
String longestString = getLongestString(toppings);
System.out.format("longest string: '%s'\n", longestString);
}
}
An easy way would be a for loop to read 5 names and find the length for largest name. Using the for loop avoids the creation of 5 deterrent string variables.
If you want to use those names later you can go for String array.
public static void main(String[] args) throws IOException {
Scanner x = new Scanner(System.in);
String name = "";
String maxName = "";
int maxLength = 0;
System.out.println("enter 5 name :");
for (int i = 0; i < 5; i++) { // read 5 names
name = x.nextLine();
if (maxLength < name.length()) { // check longest name
maxLength = name.length();
maxName = name; // store in temp variable to show
}
}
System.out.println("Longest name is " + maxName); // print largest name
}
Output:
enter 5 name :
raj
sita
gita
mukherjee
rita
Longest name is mukherjee
Here's a solution that should work with any number of entries:
Scanner x = new Scanner(System.in);
String name = "", temp="";
while (x.hasNextLine()){
temp = x.nextLine();
if (temp.length() > name.length()) name = temp;
}
System.out.println("Longest is " + name);
You'll need to Ctrl + Z to end the inputStream on Windows
this is my code for comparing 3 input strings by their length:
public static void main(String[] args) {
String string1 , string2 , string3;
Scanner input = new Scanner(System.in);
System.out.println("Enter three string names to compare");
string1 = input.nextLine();
string2 = input.nextLine();
string3 = input.nextLine();
if (string1.length()>string2.length()) {
if (string1.length() > string3.length())
System.out.println("String 1 has the longest length , length = "+string1.length());
}
if (string2.length()>string1.length()){
if(string2.length()>string3.length())
System.out.println("String 2 has the longest length , length = "+string2.length());
}
if (string3.length()>string1.length()) {
if (string3.length() > string2.length())
System.out.println("String 3 has the longest length , length = " + string3.length());
}
}
//SIMPLE JAVA SOLUTION
class GFG
{
String longest(String names[], int n)
{
String res="";
for(int i=0;i<n;i++)
{
if(res.length()<names[i].length())
{
res=names[i];
}
}
return res;
}
}
Related
When I insert the arguments the search always returns "not found" - even though the searched value was input into the array?
import java.util.Scanner;
public class assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] BookID = new String [3];
String [] Booktitle = new String [3];
//input the BookID
System.out.println("Enter the 12 BookID");
for (int a = 0 ; a < BookID.length; a++)
{
System.out.print("BookID :");
BookID[a] = sc.next();
}
//Input the book title
for (int b = 0 ; b < Booktitle.length ; b++)
{
System.out.print("Booktitle :");
Booktitle[b] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter BookID to find :");
for(int c = 0; c < BookID.length; c++)
{
searchValue = sc.next();
if(searchValue.equals(BookID))
System.out.print("BookID is found : ");
else
System.out.print("BookID is not found : ");
}
}
}
I'm expecting the result to return like so: if input BookID 112. The Linear search would return "The BookID is found :" instead of the else statement.
Try printing out the value of the bookId you wanna find to see if there anything with the string that could cause it to not be equals. Also, you could convert the string to an integer with:
Integer.parseInt("BookId");
The equals would have less chance of failing, you could also change de the array for an array of int instead of String.
This code has some basic things right, but it could be a bit better. Some of the changes I made are for keeping Java conventions (so the code is easier to read and understand) and some are functional. I added them as comments.
import java.util.Scanner;
public class Assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] bookIDs = new String [3]; //lowercase for the attribute name (convention)
String [] bookTitles = new String [3]; //plural for the array (convention)
//input the BookID
System.out.println("Enter the Book ID");
for (int i = 0 ; i < bookIDs.length; i++) { //you can re-use the i in all loops
System.out.print("Enter " + i + " Book ID: ");
bookIDs[i] = sc.next();
}
//Input the book title
for (int i = 0 ; i < bookTitles.length ; i++) {
System.out.print("Enter " + i + " Book title: ");
bookTitles[i] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter Book ID to find: ");
searchValue = sc.next(); //NOTE: this is your first mistake. read out of the loop
for(int i = 0; i < bookIDs.length; i++) {
if(searchValue.equals(bookIDs[i])) { //NOTE: this is your second mistake - you wanted the array value, not the array
System.out.println("BookID is found in position "+i);
break; //suggestion - stop the loop when found.
}
else {
System.out.println("BookID is not found in position "+i);
}
}
sc.close(); //NOTE: important to close scanners at the end.
}
}
Good luck with your studies.
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
I'm trying to read a sentence in Java and to know how many words are in there. This is what I've done:
public class TestWords {
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr=new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
int TotalSizeOfPhrase = Phrase.length();
double number;
for (int i=0; i < TotalSizeOfPhrase; i++)
{
if (Phrase[i] != number && Character.isWhitespace(s.charAt(i)))
{
TotalWords = TotalWords + 1;
}
}
}
}
And I'd like to know how to code this:
if (Phrase[i]!= 'of an **arbitrary** number && white space')
then:
TotalWords = TotalWords + 1;
Because it marks a mistake when I type this:
Character.isWhitespace(s.charAt(i))
There are couple of mistakes
System.out.println("Give your phrase : ");
Scanner scan = new Scanner(System.in);
String Phrase;
Phrase = scan.nextLine();
System.out.println("Enter age : ");
int number = scan.nextInt();
// replace the number with empty string mean nothing
Phrase = Phrase.replace(String.valueOf(number), "");
Phrase = Phrase.concat(" "); // add space at end for loop calculation
int TotalSizeOfPhrase = 0; // set tot =0
int count=0; // a count variable to keep track of the word length
for (int i=0; i<Phrase.length(); i++)
{
count++;
if(Character.isWhitespace(Phrase.charAt(i)))
{
if(count-1>1){ // if size of word ( -1 is there for space size)
// is greater than 1 than increment count
TotalSizeOfPhrase=TotalSizeOfPhrase+1;
}
count=0;
}
}
System.out.println(TotalSizeOfPhrase);
scan.close();// don't forget
Inuput :
Hello i'm 20 and I'm a beginner
20
output :
5
The way i would do it, is to split the line by white spaces (getting the words), adding them to array and then getting this array length which would be equal to word count.
Phrase = Phrase.trim(); //make sure there is no spaces at start or end of the line
String[] words = Phrase.split(" "); //get the words
int word_count = words.length; //get the word count in line
if you want to get the number of words in the sentence , you could use this code :
int numberOfWords = Phrase.trim().isEmpty() ? 0 : trim.split("\\s+").length;
You can use this code:
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr = new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
String[] words = Phrase.trim().split(" ");
System.out.println("Totals Number Of Words: " + words.length);
for (String word : words) {
System.out.println(word.trim());
}
}
I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.
I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains.
List of people: length 3
1 : Fnjiei : ID 7868860 : Age 18
2 : Oipuiieerb : ID 334134 : Age 39
3 : Enekaree : ID 6106274 : Age 31
I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) It was able to read one single line....... but no more than a single line of text.
public void readFile(String fileName)throws IOException{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
try {
while (input.hasNextLine()){
int howMany = 3;
System.out.println(howMany);
String userInput = input.nextLine();
String name = "";
String idS = "";
String ageS = "";
int id;
int age;
int count=0;
for (int j = 0; j <= howMany; j++){
for (int i=0; i < userInput.length(); i++){
if(count < 2){ // for name
if(Character.isLetter(userInput.charAt(i))){
name+=userInput.charAt(i); // store the name
}else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 2){ // for id
if(Character.isDigit(userInput.charAt(i))){
idS+=userInput.charAt(i); // store the id
}
else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 3){ // for age
if(Character.isDigit(userInput.charAt(i))){
ageS+=userInput.charAt(i); // store the age
}
}
id = Integer.parseInt(idS); // convert id to integer
age = Integer.parseInt(ageS); // convert age to integer
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
userInput = input.nextLine();
}
}
}finally{
if (input != null){
input.close();
}
}
}
My appology if my mere code begs to be changed.
Edited It gives me a number format exception!!!
I dont know how many empty space would be there between these values.
Here's a solution that uses only Scanner API, the important one being findInLine. It can handle minor syntactic variations in the input format, and yet it's very readable, requiring no need for fancy regex or magic array indices.
String text =
"List of ##%^$ people : length 3 !#%# \n" +
"1 : Fnjiei : ID 7868860 ::: Age 18\n" +
" 2: Oipuiieerb : ID 334134 : Age 39 (old, lol!) \r\n" +
" 3 : Enekaree : ID 6106274 => Age 31\n";
Scanner sc = new Scanner(text);
sc.findInLine("length");
final int N = sc.nextInt();
for (int i = 0; i < N; i++) {
sc.nextLine();
sc.findInLine(":");
String name = sc.next();
sc.findInLine("ID");
long id = sc.nextLong();
sc.findInLine("Age");
int age = sc.nextInt();
System.out.printf("[%s] %s (%s)%n", id, name, age);
}
This prints:
[7868860] Fnjiei (18)
[334134] Oipuiieerb (39)
[6106274] Enekaree (31)
API links
Scanner.findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Use this Pattern.compile overload if performance is an issue
This seems to be shorter:
public void readFile(String fileName)throws IOException
{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
String userInput;
try
{
while (input.hasNextLine())
{
userInput = input.nextLine().trim();
if (userInput.length() > 0)
{
String[] userInfo = userInput.split(":");
int count = Integer.parseInt(userInfo[0].trim());
String name = userInfo[1].trim();
int id = Integer.parseInt(userInfo[2].trim().split("\\s+")[1].trim());
int age = Integer.parseInt(userInfo[3].trim().split("\\s+")[1].trim());
System.out.println("Count: " + count + " Name: " + name + " ID:" + id + " Age:" + age);
}
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
}
finally
{
if (input != null)
{
input.close();
}
}
}
For the input you have us, it prints this:
Count: 1 Name: Fnjiei ID:7868860 Age:18
Count: 2 Name: Oipuiieerb ID:334134 Age:39
Count: 3 Name: Enekaree ID:6106274 Age:31
More information about the split method can be found here. I basically first split the line by using the : as delimiter, then, I split again using the \\s+, which basically splits a string and return an array containing the words that were separated by white spaces.
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader("filename")));
try{
while(input.hasNextLine()){
String userInput = input.nextLine();
String[] data = userInput.split(":");
System.out.println("Name: "+data[1]+" ID:"+data[2].split("\\s+")[2]+
" Age:"+data[3].split("\\s+")[2]);
}
}finally{
if(input != null)
input.close();
}
Above snippet shows the basic idea.Also please keep in mind that this might not be the optimal solution.