How to read input from user with unknown length? - java

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

Related

I can't add a string to itself

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before
everything else seems to work
package chucknorris;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
String letter = input.substring(current, current);
output = output + letter + " ";
if (current == length) {
System.out.println(output);
}
}
}
}
Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
for (int current = 0;current <= length;current++) {
if (current >= length) {
break;
}
String letter = input.substring(current, current + 1);
output = output + letter;
}
System.out.println(output);
}
}
use concat for the string concatenation.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input string:");
String input = scanner.nextLine();
int length = input.length();
String output = "test";
output = output.concat(output).concat(input).concat("");
System.out.println(output);
}

At a lost on real basic value from one method to another

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.

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

Resource leak: 'sc' is never closed

Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}

Loop in Java that takes 2 values in from the String

I need to write a loop that takes in two values from the user-given list and then work with those values in the loop. My issue is that I can not seem to get the loop to take in the 2 values from the String.
Here is my code:
import java.util.Scanner;
public class practice2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter numbers seperated by commas");
String numbers = input.nextLine();
Scanner s = new Scanner(numbers);
s.useDelimiter(",");
for(int i =0; i<numbers.length(); i+=2 ) {
int newnum = i/25;
System.out.println(newnum);
}
}
}
Here, to get the values - do as below
public static void main(String[] args) {
System.out.println("enter numbers seperated by commas");
Scanner input = new Scanner (System.in);
String[] numbers = input.nextLine().split(",\\s*");
//to read number
System.out.println(numbers[0] + " - " + numbers[1]);
//to use them as int
int i = Integer.parseInt(numbers[0]);
System.out.println(++i);
}

Categories

Resources