For looping to add variables for a Scanner input - java

So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?

You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}

Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}

Related

Java program for splitting strings with line breaks and stops with no entry not working?

This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.

It only gives one string as the output

If I enter 3 objects
aakash
12323
aakshit
24r352
rahul
12323
If i give this as a input and enter search string as 'aa' then it gives only first string that matches the search ouput will be
aakash
12323
why not aakshit also
import java.util.Scanner;
import java.io.*;
public class DA_2_searching {
String name,phone_number;
Scanner s = new Scanner(System.in);
DA_2_searching()
{
System.out.print("Enter the Details");
name=s.nextLine();
phone_number= s.nextLine();
}
void search()
{
String search;
search=s.nextLine();
if(name.startsWith(search))
{
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n= s.nextInt();
DA_2_searching obj[]= new DA_2_searching[n];
for(int i=0;i<n;i++)
{
obj[i]= new DA_2_searching();
}
for(int i=0;i<n;i++)
{
obj[i].search();
}
}
}
The reason for your problem is, that you only search for one object at a time. Your for loop that calls the search() function only compares one object to a search input at a time.
In the for loop, you are only calling the search function for one DA_2_searching object (the one with index i - obj[i]). But you want to search in every DA_2_searching object you created, that means you have to rework the search() function so that it gets all DA_2_searching objects and compares them to the search-String.
Here's my solution:
import java.util.Scanner;
public class DA_2_searching {
private String name, phone_number;
private static DA_2_searching[] allPersons;
private static Scanner s = new Scanner(System.in);
public DA_2_searching() {
System.out.println("Enter the Details: ");
System.out.print("Name: ");
this.name = s.next();
System.out.print("Phone-Number: ");
this.phone_number = s.next();
System.out.println("\nNext: ");
}
public static void search() {
System.out.println("Type a word to search for: ");
String toSearch = s.next();
for(DA_2_searching person : allPersons) {
if(person.name.contains(toSearch)) { //contains is better for searching.
System.out.println("Result: " + person.name + " | " + person.phone_number);
}
}
System.out.println("\n");
if(!toSearch.equals("exit")) {
search();
}
}
public static void main(String args[]) {
System.out.print("Amount of Entries: ");
int n = s.nextInt();
System.out.println("");
allPersons = new DA_2_searching[n];
//Creating Persons
for(int i = 0; i < n; i++) {
allPersons[i] = new DA_2_searching();
}
//initializing search
search();
}
}
In your current code you search for a String in every iteration. You read in a String and check if this String equals Array[0] then you print it. Then you read in a String again and check if it is equal to Array[1]... and so on. What you want is a search in the whole Array.
A simple solution would be to read in the String before the 2nd loop and pass the
string into search();
void search(String search) {
if (name.startsWith(search)) {
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
DA_2_searching obj[] = new DA_2_searching[n];
for (int i = 0; i < n; i++) {
obj[i] = new DA_2_searching();
}
String search = new String();
search = s.nextLine();
for (int i = 0; i < n; i++) {
obj[i].search(search);
}
}

How to find if a string entered into scanner is in an array?

I have to:
Prompt the user for a string,
if the string entered is in the array "names", print out its index,
if not in names, print out "NOT FOUND"
this is what I have:
This is for my programming final and i can't figure out how to do this because I missed 1 class...
import java.util.Scanner;
public class Final1 {
public static void main (String[] args) {
int y;
int x=0;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
y=s.nextInt();
for (String a: names){
if (a.equals(y))
System.out.println(y);
}
}
}
Use Array.asList(yourArray).contains(yourValue):
import java.util.*;
public class Final1
{
public static void main (String[] args)
{
int y = 0;
int x = 0;
String name = "";
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
name = s.nextLine();
if(Arrays.asList(names).contains(name)) // Check this line
{
System.out.print(name);
}
}
}
If you are trying to print the index of it instead of the actual name again you will have to modify it a bit.
import java.util.*;
public class Final1
{
public static void main (String[] args)
{
int y = 0;
int x = 0;
String name = "";
boolean found = false;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
name = s.nextLine(); // get a string instead of an int
// likely the way your professor would like you to do this
// there are many ways, but this is the quickest while using a simple array
// you could cast it to a list
for(int i=0; i<names.length; ++i){
if(names[i].equals(name)){
System.out.print(i);
found = true;
}
}
if(!found)
System.out.println("NOT FOUND");
}
}
Edit: You could also use the Arrays static class.
int result = Arrays.binarySearch(names, name);
if(result > 0)
System.out.println(result);
else
System.out.println("NOT FOUND");
The problem is that you get user input as int.
User input values are String in order to check names since names are contained in a String array.
You can try this:
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
String y;
int x=0;
int found = 0; //to identify the index
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
y=s.nextLine();
for (String a: names){
if (a.equals(y))
{
System.out.println("index of "+a+" is :"+x);
found++; // increment if found
}
x++;//iterate each time to get the index
}
if(found == 0)// check if it is not found
System.out.println("NOT FOUND");
}
}
Output:
Enter String Name:charley
index of charley is :2
You are comparing int y with scanned Integer. y should be a string and you should scan for a String.
Try this:
import java.util.Scanner;
public class Final1 {
public static void main (String[] args) {
int x=0;
Scanner s = new Scanner(System.in);
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
System.out.print("Enter String Name:");
String y=s.nextLine();
for (String a: names){
if (a.equals(y))
System.out.println(y);
}
}
}
Your y should be a String and you should input it with an s.nextLine(). Currently you are matching integers and strings. You could use the indexOf
int index = Arrays.asList(names).indexOf(s.nextLine());
return index > -1 ? "Not found" : Integer.toString(index);

Cant understand why i am getting an infinite loop. Java. How to trigger EoF without typing exit

I am very new to java and this community. I am looking for someone to possibly be able to explain why my code is going into an infinite loop. I believe it has something to do with my while loop. The program compiles but when I enter a phrase i want for my acronym builder to create the program dosent do anything, it just blinks at the next line. When i press ctrl c to exit, it then shows the acronym.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
while (input.hasNext() )
{
phraseToChange = input.next();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The problem is not truly caused by your while loop but because the fact that scanner will keep asking user new input (system.in stream will always open) until EOF. Therefore, the problem can be solve using StringTokenizer if it's allowed by your professor. Down here is the code example
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
boolean phraseToChange2 = true;
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String nextLine = input.nextLine();
StringTokenizer st = new StringTokenizer(nextLine, " ");
while (st.hasMoreTokens())
{
phraseToChange = st.nextToken();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
System.out.println("reach here");
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The reason of why your loop never ends it the fact that System.in stream is always open. You should change the condition to while (!phraseToChange.equals("exit")) or something. Then the user will be able to finish the input by sending "exit" string to your program.
If you don't have to use a while loop with input.hasNext() you can use this. May want to clean up where necessary, but I believe this does what you want.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym {
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char[100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0; i < wordCounter; i++) {
System.out.print(acroynmArray[i]);
}
}
}
Sample build output:
run:
This program builds acronyms
Enter a phrase:
Google Rocks Socks
GRSBUILD SUCCESSFUL (total time: 4 seconds)
Code snippet that causes the change:
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
Alternatively you could use this:
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String line = input.nextLine(); // Obtain user entered line
acroynmArray[0] = line.charAt(0); // First letter is known; set it
wordCounter++; // increment wordCounter
//Loop the characters in the retrieved line
for(int i = 0; i < line.length(); i++){
// If it's whitespace then we know the next character must be the letter we want
if(Character.isWhitespace(line.charAt(i))){
acroynmArray[wordCounter] = line.charAt(i+1); // Set it
wordCounter++;
}
}
But as Tom said in my deleted post, this is quite fragile code. It works, until it doesn't, as in it wouldn't take much to break it as it doesn't handle trailing and starting whitespaces

Java vector size()

I have a tutorial work based on vectors in java se. The task is to prompt the user to input ten words in a string and then we are supposed to split the words into single words and add each of them into a vector element. However, right at the beginning, I'm already facing problems with my codes. Right now, I even have problem finding out the size of the vectors so could you guys help me out here? Thanks!
import java.util.*;
class TenWords
{
public static void main (String [] args)
{
Vector <String> words = new Vector <String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
while(userInput.hasNext())
{
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}
In this case userInput.hasNext() always returns true. So you need a finite loop. Use for loop
import java.util.Scanner;
import java.util.Vector;
public class TenWords {
public static void main(String[] args) {
Vector<String> words = new Vector<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
for (int i = 0; i < 10; i++) {
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}

Categories

Resources