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
Related
first question here.
So for both of these loops I am looking for the user to input a value less than 10 for loop 1 and less than 200 for loop 2. It is almost working to my liking however when a user enters an incorrect number the loop just exits where it should repeat and ask the user for another digit smaller than 10/200.
Any assistance is greatly appreciated.
public class Main {
public static int numberOfStars;
public static void main(String[ ] args){
//ask for number of stars (user-input)
System.out.println("Enter the number of stars in your constellation");
Scanner stars = new Scanner(System.in);
if (numberOfStars <= 10) {
numberOfStars = stars.nextInt();
}do{
System.out.println("The number of stars is : " + numberOfStars);
} while (numberOfStars <= 10);
//ask for location of stars (user-input)
System.out.println("Enter X and Y co-ordinates for your constellation");
//obj 1
Scanner myObj = new Scanner(System.in);
while(myObj.nextInt() <= 200) {
int location = myObj.nextInt();
System.out.println("X coordinate 1 is : " + location);
} do {
System.out.println("Please enter a Number Less than 200");
} while (myObj.nextInt() > 200 );
You could put all the code in your main mathod in a while(true) loop as you are invoking a blocking method. If you succeed (if the value is correct) you can just break the main loop (e.g. by marking it with a label). Otherwise continue the main loop which makes the input prompt appear again.
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;
}
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 + " ");
}
}
}
I'm a beginner in Java programming, and I have an assignment on while loops.
The assignment was to have windows open up with the numbers 1-10 on display.
The first two, I got down. The third one was to have the user enter a number 'x', and the next window was to show all integers between 1 and 'x' using a while loop.
As I have it coded now, each loop iteration pops up in it's own window, instead of all at once, in one window.
TL;DR I want to have 1 window with 10 loops, not 10 windows with 1 loop each.
JOptionPane and while loops were in the handouts and notes he had us take, but no mention of how to combine them.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text=JOptionPane.showInputDialog("Please enter a number: ");
int f,x;
f=0;
x=Integer.parseInt(text);
while (f<=x)
{//What am I doing wrong between here
JOptionPane.showMessageDialog(null, f);
f++;
}//and here?
}
}
I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text = JOptionPane.showInputDialog("Please enter a number: ");
int f, x;
//if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
f = 1;
x = Integer.parseInt(text);
StringBuilder sb = new StringBuilder();
while (f <= x)
{
//rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
sb.append(f).append("\n");
//JOptionPane.showMessageDialog(null, f);
f++;
}
//string builder has a "\n" at the end so lets get rid of it by getting a substring
String out = sb.substring(0, sb.length() - 1);
JOptionPane.showMessageDialog(null, out);
}
}
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);
}
}