java 要求输入一个数字(例如2)如果无效要求重新输入,输入第二个数字(0-3)
发布网友
发布时间:2022-04-30 03:43
我来回答
共3个回答
热心网友
时间:2023-10-10 02:53
import java.util.Scanner;
public class Test {
public void test(){
Scanner input1 = new Scanner(System.in);//创建系统输入实例系统
int num1 = 0;
//用do while方法可以先赋给num1一个值再判断
do{
System.out.println("请输入第一个数(0-9):");
num1 = input1.nextInt();//获取控制台输入
}while(num1>9||num1<0);//逻辑判断输入是不是0-9,否则调回重输
System.out.println("请输入第二个数:");
int num2 = input1.nextInt();//控制台获取第二个数
//循环输出num2+1次,从0开始
for(int i=0;i<=num2;i++){
System.out.println(Math.pow(num1, i));//调用系统幂次方函数num1的i次方
}
}
public static void main(String[] args) {
Test t = new Test();
t.test();
}
}
热心网友
时间:2023-10-10 02:54
package array;
import javax.swing.JOptionPane;
public class pow {
public static void main(String[] args){
String numString = JOptionPane.showInputDialog("Enter a number:");//对话框中输入数字,输入的格式为字符串类型
int num = Integer.parseInt(numString);//把字符串类型转换成整形
String countString = JOptionPane.showInputDialog("Enter the count:");//同上,输入要进行的幂次
int count = Integer.parseInt(countString);
test(num,count);//调用测试方法
}
public static void test(int m,int c){
int k = 0;
String output = " ";//输出的字符串
while(k <= c){
output += Math.pow(m, k) + " , " ;//依次把m的0-c次幂加到一个字符串上,方便输出
k ++;
}
JOptionPane.showMessageDialog(null, output);//在消息对话框中输出结果
}
}
热心网友
时间:2023-10-10 02:54
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
int base = getDigitFromInput(0, 3, true);
int exp = getDigitFromInput(0, 3, false);
for(int i = 0; i <= exp; i++){
System.out.println((int)Math.pow(base, i));
}
}
private static int getDigitFromInput(int min, int max, boolean isBase) {
int value = 0;
String baseOrExp = isBase? " base ": " exponent ";
boolean isValidInput = false;
do{
try {
System.out.println("Please input a digit as" + baseOrExp);
Scanner scanner = new Scanner(System.in);
value = scanner.nextInt();
if(!isBase){
if(value < 0 || value > 3){
System.out.println("Digit should be between 0 and 3 for exponent. Please input again!");
continue;
}
}
isValidInput = true;
} catch (InputMismatchException misMatchExp) {
System.out.println("Invalid data format for" + baseOrExp + ", Please input again!");
}
}while(!isValidInput);
return value;
}
}
----------------
Please input a digit as base
a
Invalid data format for base , Please input again!
Please input a digit as base
12.0
Invalid data format for base , Please input again!
Please input a digit as base
5
Please input a digit as exponent
cde
Invalid data format for exponent , Please input again!
Please input a digit as exponent
7
Digit should be between 0 and 3 for exponent. Please input again!
Please input a digit as exponent
3
1
5
25
125