How do i exit a loop when user enters null - java

I need to write a program that prompts the user to to enter up to 5 movie titles. User to hit enter to exit input and partially fill array.
I've tried many solutions suggested in these pages. Either the loop continues or i get boolean/string conversion errors.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String [] Movie = new String[5];
String title;
int count = 0;
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
if(sc.equals("")) {
break;
}
title = sc.nextLine();
Movie[i] = title;
count++;
}
}
for(int i=0; i < Movie.length; i++) {
System.out.println(Movie[i]);
}
}
I expect the program to input code until user hits enter then see output of what was entered.

The problem is you are comparing Scanner object with empty String which is wrong sc.equals(""). First read the input into String and them check empty or not
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
title = sc.nextLine();
if(title.equals("")) {
break;
}
Movie[i] = title;
count++;
}
}
To just print an array use Arrays.toString
System.out.println(Arrays.toString(Movie));

You should not nest two loops for reading the input, you need one loop with two conditions; the count must be less than the Movies array length (which should be named movies to follow Java naming conventions) and there needs to be another line for the Scanner. I would prefer String.isEmpty() to String.equals(""). And your second loop should stop at count (since entries after that are potentially blank). Something like,
Scanner sc = new Scanner(System.in);
String[] movies = new String[5];
int count = 0;
for (int i = 0; i < movies.length && sc.hasNextLine(); i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
String title = sc.nextLine();
if (title.isEmpty()) {
break;
}
movies[count] = title;
count++;
}
for (int i = 0; i < count; i++) {
System.out.println(movies[i]);
}

import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
}
}
System.out.println(Arrays.toString(Movie));
}
}

import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
int count = 0;
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
count++;
}
}
System.out.println("Movie Titles:\n");
for(int j = 0 ; j < count; j++)
System.out.printf("%s\n", Movie[j]);
}
}

Related

Want to print my stored names in array by JoptionPane, JAVA

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);
}
}

How do you connect a single scanner to two arrays?

Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.

Scanner input and array duplicates verification causes an infinite loop

I code a program that lists entered names. But if the entered name is already in the array, the user has to reenter a different name.
I left a picture below that shows what is happening when I run the code
import java.util.Scanner;
public class list {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name:");
list[i] = al.nextLine();
for (int j = 0; j < i; j++) {
if (list[i] == list[j]) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}
}
Your issue is this line:
if (list[i] == list[j])
This checks if the 2 objects are equal, which they are not even if their content is the same. You need to use .equals method of String object to compare 2 strings. That should fix the problem:
if (list[i].equals(list[j]))
I would rather use a Set of String instead of an array for a better performance since you won't have to iterate over and over again for each new input. Something like:
Set<String> set = new HashSet<>();
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name: ");
String name = al.nextLine();
while (set.contains(name)) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
System.out.print("Enter the name: ");
name = al.nextLine();
}
set.add(name);
}
Looking into your code, i found that you are using al.nextLine() which can return an empty String if the previous element the Scanner gave you was not a whole line. This is why you get prompted twice to enter a name when you run your program. See this post for further details.
Solution: use al.next() instead.
You are also comparing two String with the == operator which is comparing their adresses in memory. This comparison will always return false
Here is as working program:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name:");
list[i] = al.next();
for (int j = 0; j < i ; j++) {
if (list[i].equals(list[j])) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}

Run Time Error_String index out of bound Exception_Printing string odd and even indexes

Code :
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sa = new String[n];
for(int i=0;i<n;i++){
sa[i] = sc.nextLine();
}
String odd="";
String even="";
for(int i=0;i<n;i++)
{
for(int j=0;j<sa[i].length();j++)
{
if(j%2!=0){
odd = odd+sa[j].charAt(j);
}
else {
even = even+sa[j].charAt(j);
}
}
System.out.println(odd+" "+even);
}
}
}
ISsue : GEtting run time exception while running the code. --> String index out of bound exception
You can try below code. It is because of calling a method like nextInt() before sc.nextLine()
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.
You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array size");
int n = Integer.parseInt(sc.nextLine());
String[] sa = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element "+i);
String val = sc.nextLine();
sa[i]=val;
}
String odd = "";
String even = "";
for (int i = 0; i < n; i++) {
for (int j = 0; j < sa[i].length(); j++) {
if (j % 2 != 0) {
odd = odd + sa[j].charAt(j);
} else {
even = even + sa[j].charAt(j);
}
}
System.out.println(odd + " " + even);
}
}

Java: How do I replace a string element from an array

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]);
}
}
}

Categories