How do I make this program run until the user enters a specific key, lets say x, to terminate the program?
public class NestedLoopTableApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Table Numbers [one at a time]");
int valueOne = sc.nextInt();
int valueTwo = sc.nextInt();
NestedLoopTable np = new NestedLoopTable(valueOne, valueTwo);
np.printTable();
sc.close();
}
}
Just add your code block into the while loop and add a condition
while(sc.nextLine().equals("x")) {
//...... your code here
}
Thanks,
Vijay Kareliya
Related
I'm not allowed to use any loops in my assignments lately, which has me stumped on this latest assignment. I'm supposed to ask the user for a series of integers, indefinitely, until they enter a non-integer, then inform them of the greatest integer. This following code, however, only takes in a single input:
public class GreatestNumber {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int a;
int g=0;
System.out.println("Enter several numbers. Enter a non-integer to end.");
if(in.hasNext()){
try{a=in.nextInt();
g=Greatest(a); }
catch (NumberFormatException e){
System.out.println("Greatest number in that sequence is "+g);
}}}
public static int Greatest(int x){
int g=0;
if (x>g){
g=x;
}
return g;
}
}
That is a lot of code. You could use recursion. Define greatest as taking a Scanner, check for an int and recurse with Math.max(int, int). Like,
public static int greatest(Scanner in) {
if (in.hasNextInt()) {
return Math.max(in.nextInt(), greatest(in));
}
return Integer.MIN_VALUE;
}
Then to call it, you only need something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter several numbers. Enter a non-integer to end.");
System.out.println("Greatest number in that sequence is " + greatest(in));
}
Last objective of my assignment asks to create a method matches(). It receives another GenericMemoryCell as a parameter, and returns true if both of its stored values can be found in the stored values of the current GenericMemoryCell. Order of stored values is not important.
Creating the method was not difficult, but I am lost on how to call it from main() because I cannot wrap my head around the concept of passing another instance of GenericMemoryCell. Where am I getting another pair of storedValueA and storedValueB in the first place? Is matches() "running" a virtual instance of the entire program within itself?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
I think you need something like this
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
Hopefully, it might work for you. However, if you want system to ask for inputs repeatedly, you need to some kind of loop.
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}
So I'm trying to make a program where the user inputs a number and the computer outputs the factorial. I have to use recursion and have 1 class and 1 client.
My class is:
public class Factorial
{
public static int Factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*(Factorial(n-1));
}
}
}
My client is:
public class FactorialClient
{
public static void main()
{
Factorial n = new Factorial();
System.out.println(n.Factorial(4));
}
}
These both compile and work completely fine. However, I'm trying to figure out a way for the user to input the number instead of my inputting the number inside the client. Please help!
Try this.
public class FactorialClient
{
public static void main()
{
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int x = reader.nextInt();
Factorial n = new Factorial();
System.out.println(n.Factorial(x));
}
}
The Scanner class is great for reading user input.
The following should work:
public class FactorialClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();
System.out.println(Factorial.Factorial(userInput));
}
}
Note that you don't have to declare a new Factorial object because the Factorial method has been declared static.
public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}
I wanted to program a java app that can print as many stars as the user want.
The programm will ask the user how many starts he want to print.
Here is my code :
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input = new Scanner(System.in);
System.out.println("How many stars do you need?");
StarsN= input.nextInt();
}
public static void loopz(String[] args) {
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart==loopEnd;loopStart++) {
System.out.print("*");
}
}
}
First thing to note.. I don't know why you are sending your loopz method a String[].. Here is what i would do differently in the loopz method:
public static void loopz(int numOfStars)
{
for(int i = 0; i < numOfStars; i++)
System.out.print("*");
}
Also call loopz in main and send it the parameter.
your for loop : loopStart = 0 then it says is loopStart == loopEnd , and it won't enter in the loop because loopStart don't equals loopEnd so you should change "==" in your loop to "<" .
Here is the answer:
import java.util.Scanner;
public class lab {
public static void main(String[] args){
int StarsN;
Scanner input;
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
StarsN= input.nextInt();
int loopEnd = StarsN;
int loopStart;
for (loopStart = 0;loopStart<loopEnd;loopStart++) {
System.out.print("*") ;
}
}
}
I really would like to teach you how to fish, instead of just giving you the fish, but I think that you need too much theory before this. Try to find some book or a good and complete tutorial to follow, I'm sorry but I don't know neither of both to say to you.
Change for (loopStart = 0;loopStart==loopEnd;loopStart++) to for (loopStart = 0;loopStart < loopEnd;loopStart++).
And don't forget to call loopz() from main():
public static void main(String[] args){
Scanner input = null;
try {
input=new Scanner(System.in);
System.out.println("How many starts do you need ?");
int StarsN= input.nextInt();
loopz(StarsN); //Add this
} finally {
if( input != null )
input.close();
}
}
public static void loopz(int numStars) { //You don't need the String[] args here since you never use it
for (int loopStart = 0; loopStart < numStars;loopStart++) {
System.out.print("*") ;
}
}