Java loop scanner input until enter or "e" without .split - java

public class test {
private static Scanner userpress = new Scanner(System.in);
public static void main(String[] args) {
int r = 0;
int h = 0;
System.out.println("---------------------------------");
System.out.println("write your two numbers (numerator, denominator)");
userpress.useDelimiter("\\s"); // here
while (userpress.hasNextInt()) {
r = userpress.nextInt();
h = userpress.nextInt();
// userpress.nextLine(); // remove
int x = r / h;
System.out.print(x + " ");
}
}
private static void message() {
System.out.println("user pressed e");
}
}
This program asks the user for minimum of 2 inputs, the first input is numerator and the second will be denominator, then it will give the value of numerator/denominator and print it out.
Here is what i want to be able to do: I want to be able to write down as many numbers as possible, for example 10 5 20 4, the output should be 2, 5 and if i write 10 5 20 4 30 5 the output should be 2, 5, 6. however this only works for even numbers. if i write uneven numbers for example 10 5 3, then the program crashes because 2 is not being divided by anything. I want the program to delete the last input if its uneven, for example if input is 10 5 3, then output should be 2 since 10/5=2 and the last input should be disgarded. How do I solve that issue?
problem number 2: If i write an e after the numbers, for example; 10 5 20 4 e, then I want the output to be 2, 5 user pressed e
I dont want to use .split and i have to use hasnext... and next()

The problem with your code is that you are scanning two integers with a single check of userpress.hasNextInt(). This check should be there for every scan of an integer.
The working code:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int r = 0;
int h = 0;
System.out.print("Write your two numbers (numerator, denominator): ");
Scanner userpress = new Scanner(System.in);
userpress.useDelimiter("\\s");
while (userpress.hasNextInt()) {
r = userpress.nextInt();
if (userpress.hasNextInt()) {
h = userpress.nextInt();
int x = r / h;
System.out.print(x + " ");
} else {
break;
}
}
String s = userpress.next();
if ("e".equalsIgnoreCase(s)) {
message();
}
}
private static void message() {
System.out.println("user pressed e");
}
}
A sample run:
Write your two numbers (numerator, denominator): 10 5 3 e
2 user pressed e
Another sample run:
Write your two numbers (numerator, denominator): 10 5 3
2
Another sample run:
Write your two numbers (numerator, denominator): 10 5 20 5
2 4
Another sample run:
Write your two numbers (numerator, denominator): 10 5 20 5 e
2 4 user pressed e

You can use regex for checking spaces and than take the only first part before space.
Like this :
import java.util.Scanner;
public class Main {
private static Scanner userpress = new Scanner(System.in);
public static void main(String[] args) {
String first;
String second;
System.out.println("---------------------------------");
System.out.println("write your two numbers (numerator, denominator)");
userpress.useDelimiter("\\s"); // here
while (userpress.hasNextLine()) {
first = userpress.nextLine();
second = userpress.nextLine();
if(first.contains(" ") || second.contains(" ")) {
String[] firstParts = first.split(" ");
String[] secondParts = second.split(" ");
first = firstParts[0];
second = secondParts[0];
}
// userpress.nextLine(); // remove
int x = Integer.valueOf(first) / Integer.valueOf(second);
System.out.print(x + " ");
}
}
private static void message() {
System.out.println("user pressed e");
}
}

Alternatively, if you would not mind using a little bit more space, you could come up with a simple algorithm, like:
public class Main {
private static Scanner userpress = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("---------------------------------");
System.out.println("write your two numbers (numerator, denominator)");
userpress.useDelimiter("\\s");
List<Integer> numbers = new ArrayList<>();
while(userpress.hasNextInt()) {
numbers.add(userpress.nextInt());
}
for (int i=0; i<numbers.size()-1; i+=2) {
int x = numbers.get(i)/numbers.get(i+1);
System.out.print(x + " ");
}
}
}

Related

How to multiply different indexes by different values?

I am creating a scrabble game, where the characters get the same values as scrabble,(q & z =10),(k=5), etc, and the main issue that I am having is that I am asking the user to input 2 ints after the word, the first being the index of the bonus tile, and the second being the multiplier to multiply the word with. The value without the multiplier is correct, but the multiplier is not working.
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String word = kb.next();
int bonusI = kb.nextInt();
int bonusMult = kb.nextInt();
int score=0;
for (int i=0; i<word.length();i++){
int letterScore;
String letter=word.substring(i,i+1);
if (letter.equals("d")||letter.equals("g")){
letterScore=2;
}
else if (letter.equals("k")) {
letterScore=5;
}
else if (letter.equals("j")||letter.equals("x")){
letterScore=8;
}
else if (letter.equals("q")||letter.equals("z")) {
letterScore=10;
}
else {
letterScore=1;
}
for (int j=0;j<1;j++){
if (word.substring(i,i+1).equals(bonusI)){
letterScore*=bonusMult;
}
}
score+=letterScore;
}
System.out.println(score);
}
}
For example, if the input is dog 2 3 then the correct output would be 9,(d is 2 points,o according to scrabble is 1 point, and g is 2 points, but since the 1st int inputted was 2, and g has an index of 2, it is then multiplied by the bonus of 3, which makes g=6, adding them 2+1+6=9) but instead my output is 5 because the multiplier for g is not working.
Looks like you have a mistake here.
word.substring(i,i+1).equals(bonusI)
word.substring(i,i+1) is String and gives one letter
bonusI is an int and tives one number
This will never be true
if (word.substring(i,i+1).equals(bonusI)) - This condition will be always false as you can't compare a string with int value.
Instead you can just replace the internal for loop with below code
if (bonusI == i)
{
letterScore*=bonusMult;
}

I need a loop to ask user 5 times for a number between 1 and 10

In this function, I need a loop that asks the user for 5 numbers between 1 and 10 and stores the numbers in an array call numArray. I need validation on the user's input. I know I need another loop somewhere that will allow the user to enter 5 different numbers, but I don't know where to put it.
public class numberInput {
static int number;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// Calls inputNumbers function
inputNumbers();
}
// inputNumbers function
public static void inputNumbers() {
System.out.println("Please enter 5 numbers between 1 and 10.");
number = keyboard.nextInt();
// If below is true display error message
while (number <= 0 || number > 10) {
System.out.println("Error: Enter a number BETWEEN 1 and 10.");
number = keyboard.nextInt();
}
}
}
Just like this, ask for 5 distinct numbers:
public static void inputNumbers() {
ArrayList<Integer> al = new ArrayList<Integer>();
System.out.println("Please enter 5 distinct numbers between 1 and 10.");
for(int i = 0;i<5;i++) {
number = keyboard.nextInt();
// If below is true display error message
while (number <= 0 || number > 10 || al.contains(number)) {//al.contain(number) means does al have number in it
System.out.println("Error: Enter a number BETWEEN 1 and 10.");
number = keyboard.nextInt();
}
al.add(number);//now add the number into the arraylist
}
}
If you want an array, do:
int[] numArray = new int[];
numArray = al.toArray(new int[0]);

Working with week days and finding future days

I am trying to find means to compute future weekdays, given two inputs:
Current weekday (range from 0-6 where 0 is Sunday).
How many counts to perform from current weekday (any number)?
Here if the user previously starts from current weekday = 3, and
counts=7.
Then I expect it to come back to 3, similarly with 14 or 21.
How to generalize this to make the counts within this fixed range
0-6 without pulling out of it?
I've already done some code which is posted below,
public class ThoseDays {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.print("Enter number between 0-6 : ");
int startFromHere = obj.nextInt();
System.out.print("Enter number to count position from " + startFromHere + " : ");
int rotateFromHere = obj.nextInt();
System.out.print( startFromHere + rotateFromHere);
obj.close();
}
}
Actual result:
> Enter the number between 0-6: 3
> Enter the number to count position from 3: 7
> 10
Expected result:
> Enter the number between 0-6: 3
> Enter the number to count position from 3: 7
> 3
Hi i suggest you just use a modulo to rotate the days after they reach 7. Another tutorial here
public class ThoseDays {
public static void main(String[] args) {
//Scanner implements AutoCloseable
//https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
try (Scanner obj = new Scanner(System.in)) {
System.out.print("Enter number between 0-6 : ");
int startFromHere = obj.nextInt();
System.out.print("Enter number to count position from " + startFromHere + " : ");
int rotateFromHere = obj.nextInt();
int absoluteNumber = startFromHere + rotateFromHere;
System.out.println(absoluteNumber);
int rotatedNumber = absoluteNumber % 7;
System.out.println(rotatedNumber);
}
}
}
code:
import java.util.*;
public class ThoseDays {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("note : 0:sun 1-6:mon-saturday");
System.out.println("Enter the number between 0-6: ");// 0:sun 1-6:mon-saturday
int startFromHere = obj.nextInt();
System.out.println("Enter the number to count position from " + startFromHere+ ": ");
int rotateFromHere =obj.nextInt();
if(rotateFromHere%7==0)
{
System.out.println(startFromHere);
}
if(rotateFromHere%7!=0)
{
int dayOfWeek=(startFromHere+(rotateFromHere%7));
if(dayOfWeek>=7)
{
System.out.println((dayOfWeek%7));
}
else
{
System.out.print(dayOfWeek);
}
}
obj.close();
}
}
try this code by changing conditions and using modulo I'm getting all correct results
output:
startFromHere = 3
rotate fromHere = 7 or 14 or 21 or multiple of 7
gives the same date as the start date
if rotate date is > start date
for ex:
startFromHere = 3 //wednesday
rotateFromHere = 11
output will be : 0 which means sunday
check this code and give me a rating if useful thanks.

Multiple values with only one scanner method?

I have an assignment where I need to do certain calculations in separate methods using data entered by the user. My problem is with the user input. It is supposed to be done with a separate method (I do not think I am allowed to use arrays for storing the inputs). The user should be able to enter as many values they want and then exit with "q". The program should then take the first two numbers, calculate e.g. an area and volume with those (with other methods I did not include here), present the result, take the next two numbers the user entered, calculate and present results. This should be repeated until it reaches the "q" value. So for example:
Enter your values: 9 5 3 7 q
radius: 9 height: 5
Area = 254
Volume = 424
radius: 3 height: 7
Area = 28
Volume = 65
A problem I am having is that only the first value is assigned to a variable and then the user has to enter data again for the next variable, even though there's still more numbers left from the first time.
import java.util.Scanner;
public class Stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int radie, height;
radie = userInput("");
height = userInput("");
}
public static int userInput(String message) {
int number = Integer.MAX_VALUE;
while (number == Integer.MAX_VALUE) {
System.out.print(message);
if (input.hasNextInt()) {
number = input.nextInt();
}
input.nextLine();
}
return number;
}
}
I understand there are massive flaws in my code here, I'm very lost and not sure where to even start with solving the problem. Any help or tips are very welcome! Thanks in advance!
Did you read 'Scanner.hasNextInt()' method documentation?
There is written:
Returns:
true if and only if this scanner's next token is a valid int value
So question if
number == Integer.MAX_VALUE
doesn't make sens.
Try to ask if hasNextInt()
returns true or false
Edit: Also
Why do you assume that after number is always 'q'?
Change condition in while statement
Don't really understand your mean, but i did some changes:
import java.util.Scanner;
public class stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
userInput();
}
public static void userInput() {
while (true) {
System.out.println("Enter your values:");
String message = input.nextLine();
//Split data with space
String[] data = message.split(" ");
int pointer = 2;
for (String i : data) {
if (i.equals("q")) {
System.out.println("Stopped.");
System.exit(0);
}
if (pointer % 2 == 0) {
System.out.println("radius: " + i);
}
if (pointer % 2 == 1) {
System.out.println("height: " + i);
}
pointer++;
}
}
}
}
Affect:
Enter your values:
1 2 3 4 5 6 7 8
radius: 1
height: 2
radius: 3
height: 4
radius: 5
height: 6
radius: 7
height: 8
Enter your values:
1 q
radius: 1
Stopped.
Process finished with exit code 0

how to get a number to add like 12 is 3

i cant get the code right to ask for a number like 12 and then say the sum of the number is 3 in java netbeans
i got this so far
public class Exercise2_6 {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner( System.in );
System.out.println("Enter a number between 0 and 1000");
// Enter a number between 0 and 1000
Scanner input = new Scanner( System.in );
int x = in.nextInt( );
System.out.println(" The sum of the digits is "n" ");
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
}
}
and it gives me back
run:
Enter a number between 0 and 1000
12
The sum of the digits is
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement
at Exercise2_6.main(Exercise2_6.java:55)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
Strings must be concatenated using the + operator.
Therefore, your statement of "n" = .... is not correct.
Replace
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
with
System.out.println("n = " + in.nextInt()/100);
System.out.println("n = " + in.nextInt()%100);
However, the above statements will refer to TWO different ints, one for each time nextInt() is called. I don't know the purpose of your code but you should get into the practice of storing variables incase you need to use them again.
If you stored each int locally, for example
int n = in.nextInt();
you could then refer to it again later, for example by appending the above statements to
System.out.println("n = " + n/100); ....
This will probably not be the most efficient or 'correct' way of doing it, but I'm a complete noob myself. So, this is how I managed it. By using a while loop.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int i, a = 0, x = 0;
System.out.println("Enter a number between 0 and 1000: ");
i = input.nextInt();
while(i != 0) {
a = i % 10;
i = i / 10;
x = x + a;
}
System.out.println("The sum of the digits in your number is: " + x);
}
}

Categories