public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}
Related
Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}
I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}
public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.
Im a newbie in java programming and I'm trying to create a program wherein the user will be asked to input words into an array depending on the number specified by the user. Afterwards, the program will be displaying the entered words in Alphabetical order. The user will also be prompted "Which word to replace from the list?" This is the part I'm having problems. I dont know how the user can enter the new word (a string element) and replace it from the list. What I was able to come up, is to input an integer representing the position of that word from the array and replace it from the list. Dont know how can I make it as string?
import java.util.Scanner;
import java.util.Arrays;
public class EnterArrays {
public static void main ( String args[] ){
int length;
Scanner sc = new Scanner(System.in);
Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = an.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}
Break your code up into smaller methods. See the (working) example below. All you need to do to change the word (string, not numeric index) with another is loop through and check for equality with the equals method. The break statement after that will stop iteration (after you've found the correct index, no point looking further).
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
Sample output:
How many words are you going to enter? 5
Enter word 1:apple
Enter word 2:banana
Enter word 3:orange
Enter word 4:pear
Enter word 5:lemon
Your words are:
apple
banana
lemon
orange
pear
Which word would you like to change? banana
You have chosen to change the word : banana
Enter the new word: strawberry
Your words are:
apple
lemon
orange
pear
strawberry
Replace the code between
System.out.println("Which word would you like to change?");
and
System.out.println("You have chosen to change the word : " +
sWordToChange);
with this:
sc.nextLine();
String sWordToChange = sc.nextLine();
int index=-1;
for (int i = 0; i < sEnterWord.length; i++) {
if(sEnterWord[i].equals(sWordToChange))
index=i;
}
Explanation:
The first line is just to avoid the scanner skipping the assignation to sWordToChange. The for loop iterates over the array and looks for a match, if it finds one it saves the index of the word on the previously declared variable index. It is initalized as -1 in case the word is not found. Maybe you want to add an if block right after the substitution to make sure you modify the array only when there is a match
Changed the Scanner class to BufferedReader Class.
public class ArrayTest {
public static void main(String args[]) throws IOException {
int length;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many words are you going to enter? ");
length=Integer.parseInt(br.readLine());
String[] sEnterWord = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println("Enter word " + (nCtr + 1) + ":");
sEnterWord[nCtr]=br.readLine();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
for (int i = 0; i < sEnterWord.length; i++) {
if (sEnterWord[i].equals(sWordToChange)) {
sEnterWord[i] = sNewWord;
}
}
System.out.println("Your words are: ");
for (int nCtr = 0; nCtr < length; nCtr++) {
System.out.println(sEnterWord[nCtr]);
}
}}
you can also make some changes in the code like:
System.out.println("Which word would you like to change?");
String sWordToChange = br.readLine();
int position = Arrays.binarySearch(sEnterWord, sWordToChange);
if (position < 0) {
System.out.println("Word not found ");
} else {
System.out.print("Enter the new word: ");
String sNewWord = br.readLine();
sEnterWord[position] = sNewWord;
}
In this program you need add sc.nextLine() before taking new word to update in String array.nextLine() method of Scanner class takes empty string from buffer.
The whole program with change of code.
package expertwebindia;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]){
int length;
Scanner sc = new Scanner(System.in);
//Scanner an = new Scanner(System.in);
System.out.print("How many words are you going to enter? ");
length = sc.nextInt();
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.print("Enter word " + (nCtr+1) + ":");
sEnterWord[nCtr] = sc.next();
}
System.out.println("Your words are: ");
Arrays.sort(sEnterWord);
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
System.out.println("Which word would you like to change?");
int sWordToChange = sc.nextInt();
sc.nextLine();
System.out.println("You have chosen to change the word : " + sWordToChange);
System.out.println("Enter the new word: ");
String sNewWord = sc.nextLine();
sEnterWord[sWordToChange-1] = sNewWord;
System.out.println("Your words are: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sEnterWord[nCtr]);
}
}
}
I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}
I am trying to do input to an array until it is full and after that print the entire array. But I cannot get the loop to run until the array is full and after that print all.
Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++){
course[i] = input.next();
grade [i] = input.nextInt();
if (i == course.length)
break;
//System.out.println("\nHow do you want to order course and grade?");
//System.out.print(" 1 - Ascending?\n"
// + " 2 - Decending?\n");
//System.out.println("Name and grade is " + course[i] + " " + grade[i]);
System.out.println(Arrays.toString(course)+(grade));
}
}
}
How can get the loop to run and then jump to the print statement?
the variable i in the loop can never be equal to course.length because the loop runs only until i < course.length. So the if block is redundant anyway.
The printing statement should be AFTER the for block, otherwise you'd be printing the array in each iteration.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String [2]; //creating array
int [] grade = new int [2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade [i] = input.nextInt();
}
System.out.println(Arrays.toString(course)+(grade));
}
There should be a } after grade [i] = input.nextInt();.
And the following if is not necessary at all.
It seems the loop would do the job if it was closed after the two assignment statements. The check afterwards isn't useful and could be removed.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] course = new String[2]; // creating array
int[] grade = new int[2];
System.out.println("Input coursename and grade: ");
for (int i = 0; i < course.length; i++) {
course[i] = input.next();
grade[i] = input.nextInt();
}
System.out.println(Arrays.toString(course) + (grade));
}
if (i == course.length) is unnecesery because when i == length then for loop finish working and for-loop-body doesn't call so remove this line and put instead of it close loop "}"
Next is printing your array. Change the last line to:
System.out.println(Arrays.toString(course) + Arrays.toString((grade)));