I'm really struggling with some basic stuff here, my userInput method basically gets an array containing 3 values, all I want to do is push that value into the convert string method. I cannot for the life of me get it to work, please help and I apologise for my stupidity
public static void main(String[] args) {
// write your code here
userInput();
convertString();
}
private static String[] userInput(String[] results) {
Scanner myUserInput = new Scanner(System.in);
//int numberOfEntries = 0;
//Boolean isValidInput = true;
String[] inPutList = new String[3];
for (int i = 0; i <= 2; i++) {
System.out.println("Please enter a letter of the alphabet");
inPutList[i] = myUserInput.nextLine();
while (!inPutList[i].matches("[A-Za-z]+")) {
System.out.println("Please enter a letter of the alphabet ony");
inPutList[i] = myUserInput.nextLine();
}
}
System.out.println("You have entered: "+ Arrays.toString(inPutList));
return inPutList;
}
private static void convertString(String[] list) {
String[] storedInput = userInput(inPutList);
System.out.println(storedInput);
}
}
The problem is that convertString expects an argument and you aren't providing one.
String[] arr = .. some values.
convertString(arr);
Is how you call it.
In your case, do this since user input returns an array.
String[] values = userInput();
convertString(values);
Change your convertString method to this. And then make the changes in main that I suggested earlier.
private static void convertString(String[] storedInput) {
System.out.println(storedInput);
}
If you want to do it by getting user inputs from converString then do it this way.
main(String[] args) {
convertString(); // no arguments needed here and none in the method.
}
And the method.
private static void convertString() {
String[] storedItems = userInput();
System.out.println(Arrays.toString(storedItems);
}
Your method calls do not match with the arguments of the method. You should do it as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
convertString();
}
private static String[] userInput() {
Scanner myUserInput = new Scanner(System.in);
String[] inPutList = new String[3];
for (int i = 0; i <= 2; i++) {
System.out.print("Please enter a letter of the alphabet: ");
inPutList[i] = myUserInput.nextLine();
while (!inPutList[i].matches("[A-Za-z]+")) {
System.out.print("Please enter a letter of the alphabet ony: ");
inPutList[i] = myUserInput.nextLine();
}
}
System.out.println("You have entered: " + Arrays.toString(inPutList));
return inPutList;
}
private static void convertString() {
String[] storedInput = userInput();
System.out.println(Arrays.toString(storedInput));
}
}
A sample run:
Please enter a letter of the alphabet: A
Please enter a letter of the alphabet: B
Please enter a letter of the alphabet: C
You have entered: [A, B, C]
[A, B, C]
As you see, you just need to call convertString from main because convertString will in turn call userInput. Moreover, I have removed the arguments from the signature of the methods to match with their calls.
Alternatively, you also do it as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
convertString(userInput());
}
private static String[] userInput() {
Scanner myUserInput = new Scanner(System.in);
String[] inPutList = new String[3];
for (int i = 0; i <= 2; i++) {
System.out.print("Please enter a letter of the alphabet: ");
inPutList[i] = myUserInput.nextLine();
while (!inPutList[i].matches("[A-Za-z]+")) {
System.out.print("Please enter a letter of the alphabet ony: ");
inPutList[i] = myUserInput.nextLine();
}
}
System.out.println("You have entered: " + Arrays.toString(inPutList));
return inPutList;
}
private static void convertString(String[] list) {
System.out.println(Arrays.toString(list));
}
}
The key is that the method call should match with its signature.
Related
import java.util.Scanner;
public class PrintVertical
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String input = in.nextLine();
int i =0;
System.out.println("Your sentence printed vertically is:");
for(i = 0; i < input.length(); i++) {
char letter = input.charAt(i);
System.out.println(letter);
}
}
}
Solution
Write a new method besides the main-method in your class and mark it with the keyword static.(Class Methods)
Give it a String as Parameter. To call it with your user input.
The Static Function:
public static void doVertic(String inp){
int i =0;
System.out.println("Your sentence printed vertically is:");
for(i = 0; i < input.length(); i++) {
char letter = input.charAt(i);
System.out.println(letter);
}
}
Then call it with your scanned input inside the main method
Call in Main Method:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String input = in.nextLine();
<Classname>.doVertic(input);
}
Note: The <Classname> have to be your Classname
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);
}
}
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);
I want to enter a string of numbers, delimited by ",". I don't know how long it will be. The input will be passed to the program and will end with the letter "x".
JAVA!
import java.util.Scanner;
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
int sumTotal=0;
while(scan.nextByte() != 'x') {
num = scan.nextInt();
sumTotal += num;
}
System.out.println(sumTotal);
scan.close();
}
}
PLEASE help! :)
//////////////
public class fromUserSum {
/// input : 1,2,4x from user
/// output : 7
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x");
userInput = scan.next();
} while (!userInput.matches("(?:\\d+(?:,\\d+)*)x") || !userInput.matches("\\d+( \\d+)*x"));
scan.close();
String[] numberStrings;
if (userInput.contains(",")) {
numberStrings = userInput.replace("x", "").split(","); // 4x is now 4 and split by ','
} else {
numberStrings = userInput.replace("x", "").split(" ");
}
int sum = 0;
for (String i : numberStrings) {
sum += Integer.valueOf(i);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
}
Try this
public static void main(String[] args) {
int result = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String string = sc.nextLine();
string = string.replace("x", "");
String[] strArray = string.split(",");
for (String str : strArray) {
result += Integer.valueOf(str);
}
System.out.println("Result is " + result);
}
Input is 1,2,3,4x
Output is Result is 10
import java.io.Console;
import java.util.Scanner;
class MainClass{
public static void main(String args[]) {
int sum=0;
Console c=System.console();
Scanner scan = new Scanner(c.readLine());
scan.useDelimiter("[,x]");
while(scan.hasNextInt())
sum+=scan.nextInt();
scan.close();
System.out.print(sum);
}
}
This does the job as well. Additionally it tells the user what input is expected and if the entered list does not match the format.
public static void main(final String[] args) {
final Scanner userInputScanner = new Scanner(System.in);
String userInput;
do {
System.out.println("Please enter a list of numbers in following format: 1,2,3,4x or 1 2 3 4x");
userInput = userInputScanner.nextLine();
} while (!(userInput.matches("\\d+(,\\d+)*x") || userInput.matches("\\d+( \\d+)*x")));
userInputScanner.close();
final String[] numberStrings = userInput.replace("x", "").split("[, ]");
int sum = 0;
for (final String numberString : numberStrings) {
sum += Integer.valueOf(numberString);
}
System.out.println("The sum of all numbers in the list is: " + sum);
}
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));
}
}